If a member method is called in constructor, this method is overridden by the quilt class, when a subclass instance is initialized, the constructor of the parent class is called, and the member method called in the context of the parent class constructor is the implementation of the parent class or the implementation of the subclass?
Can you tell exactly what these statements will print without running the code?
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.
Test:
NEW zcl_sub( )->print( ).
Test Result: 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(); }
Test results:
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();
Test results:
Detailed analysis in my SAP Community blog: A reminder for using constructor in OO world
To get more original Jerry's technical articles, please follow the public number "Wang Zixi" or scan the QR code below:
Do you really use constructor in ABAP, Java, and JavaScript?