温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

你真的会用ABAP, Java和JavaScript里的constructor么?

发布时间:2020-08-13 22:19:15 来源:ITPUB博客 阅读:156 作者:i042416 栏目:编程语言

如果constructor里调用了一个成员方法,这个方法被子类override了,当初始化一个子类实例时,父类的构造函数被的调用,此时父类构造函数的上下文里调用的成员方法,是父类的实现还是子类的实现?
你能不用运行代码,就能准确说出这些语句会打印什么出来呢?

ABAP

class ZCL_SUPER definition public
  create public .
public section.
  methods CONSTRUCTOR .
  methods SET_I
    importing
      !IV_I type INT4 .
protected section.
private section.
  data MV_SUPER type INT4 .
ENDCLASS.
CLASS ZCL_SUPER IMPLEMENTATION.
  method CONSTRUCTOR.
    me->set_i( 100 ).
  endmethod.
  method SET_I.
    me->mv_super = iv_i.
  endmethod.
ENDCLASS. class ZCL_SUB definition public
  inheriting from ZCL_SUPER
  final
  create public .
public section.
  methods PRINT .
  methods SET_I
    redefinition .
protected section.
private section.
  data MV_SUB type I value 1 ##NO_TEXT. ENDCLASS.
CLASS ZCL_SUB IMPLEMENTATION.
  method PRINT. WRITE: / ' sub:' , mv_sub.
  endmethod.
  METHOD set_i. super->set_i( iv_i = iv_i ).
    me->mv_sub = iv_i. WRITE: / 'mv_sub assigned by: ' , iv_i.
  ENDMETHOD.
ENDCLASS. 

测试:

NEW zcl_sub( )->print( ). 

测试结果:sub: 1

Java

public class SuperClass { private int mSuperX; public SuperClass() {
        setX(99);
    } public void setX(int x) {
        mSuperX = x;
    }
} public class SubClass extends SuperClass { private int mSubX = 1; public SubClass() {} @Override public void setX(int x) { super.setX(x);
        mSubX = x;
        System.out.println("SubX is assigned " + x);
    } public void printX() {
        System.out.println("SubX = " + mSubX);
    }
} 

test:

public static void main(String[] args) {
        SubClass sc = new SubClass();
        sc.printX();
    } 

测试结果:


你真的会用ABAP, Java和JavaScript里的constructor么?

JavaScript

function SuperClass(){ this.setX(99);
}

SuperClass.prototype = { mSuperX : 0, setX : function(x){ this.mSuperX = x;
    }
}; function SubClass(){  
    SuperClass.call(this); this.mSubX = 1;
}  

SubClass.prototype = new SuperClass();  

SubClass.prototype.setX = function(x){
        SuperClass.prototype.setX(x); this.mSubX = x; console.log("SubX is assigned " + x);
};

SubClass.prototype.print = function(){ console.log("SubX: " + this.mSubX);
} 

test:

var sub = new SubClass();
sub.print(); 

测试结果:


你真的会用ABAP, Java和JavaScript里的constructor么?

详细分析在我的SAP community博客里: A reminder for using constructor in OO world
要获取更多Jerry的原创技术文章,请关注公众号"汪子熙"或者扫描下面二维码:

你真的会用ABAP, Java和JavaScript里的constructor么?
你真的会用ABAP, Java和JavaScript里的constructor么?
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI