如果constructor里調(diào)用了一個(gè)成員方法,這個(gè)方法被子類override了,當(dāng)初始化一個(gè)子類實(shí)例時(shí),父類的構(gòu)造函數(shù)被的調(diào)用,此時(shí)父類構(gòu)造函數(shù)的上下文里調(diào)用的成員方法,是父類的實(shí)現(xiàn)還是子類的實(shí)現(xiàn)?
你能不用運(yùn)行代碼,就能準(zhǔn)確說(shuō)出這些語(yǔ)句會(huì)打印什么出來(lái)呢?
創(chuàng)新互聯(lián)從2013年創(chuàng)立,是專業(yè)互聯(lián)網(wǎng)技術(shù)服務(wù)公司,擁有項(xiàng)目成都網(wǎng)站設(shè)計(jì)、網(wǎng)站建設(shè)、外貿(mào)網(wǎng)站建設(shè)網(wǎng)站策劃,項(xiàng)目實(shí)施與項(xiàng)目整合能力。我們以讓每一個(gè)夢(mèng)想脫穎而出為使命,1280元互助做網(wǎng)站,已為上家服務(wù),為互助各地企業(yè)和個(gè)人服務(wù),聯(lián)系電話:13518219792
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.
測(cè)試:
NEW zcl_sub( )->print( ).
測(cè)試結(jié)果:sub: 1
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(); }
測(cè)試結(jié)果:
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();
測(cè)試結(jié)果:
詳細(xì)分析在我的SAP community博客里: A reminder for using constructor in OO world
要獲取更多Jerry的原創(chuàng)技術(shù)文章,請(qǐng)關(guān)注公眾號(hào)"汪子熙"或者掃描下面二維碼: