你真的會用ABAP, Java和JavaScript裡的constructor麼?

來源:互聯網
上載者:User

標籤:Java   JavaScript   建構函式   ABAP   Constructor   

如果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();    }

測試結果:

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();

測試結果:

詳細分析在我的SAP community部落格裡: A reminder for using constructor in OO world
要擷取更多Jerry的原創技術文章,請關注公眾號"汪子熙"或者掃描下面二維碼:

你真的會用ABAP, Java和JavaScript裡的constructor麼?

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.