1 PackageCom.zhangcy.test.init;2 3 Public classBase {4 5 intstr;6 Static intVal1=1;7 Final intval2=2;8 Static Final intVAL3 = 3;9 Ten PublicBase (Final ints) { One printstr (); ASystem.out.println ("Pre-base:" +str); -str =s; - This. PRINTSTR (); theSystem.out.println ("Aft-base:" +str); - } - - PublicBase () { + printstr (); - } + A Private voidPrintstr () { atSystem.out.println ("Base:" +str); -System.out.println ("Base-val1:" +val1); -System.out.println ("Base-val2:" +val2); -System.out.println ("Base-val3:" +val3); - } - in}
PackageCom.zhangcy.test.init; Public classDerivedextendsBase {intstr; Static intVal1=4; Final intVal2=5; Static Final intVal3=6; //Base base = new Base (str); //static Base base2 = new Base (); PublicDerived (ints) {Super(); System.out.println ("Pre-derived:" +str); STR=s; System.out.println ("Aft-derived:" +str); Printstr (); } Public voidPrintstr () {System.out.println ("Derived:" +str); System.out.println ("Derived-val1:" +val1); System.out.println ("Derived-val2:" +val2); System.out.println ("Derived-val3:" +val3); }}
PackageCom.zhangcy.test.init; Public classBasetest {/** * @paramargs*/ Public Static voidMain (string[] args) {//TODO auto-generated Method Stub /*float f = (short) 10/10.2f*2; Double d = (short) 10/10*2;*/Derived Derived=NewDerived (1); //derived = new derived (10); //Derived derived1 = new Derived (a);Base base =NewDerived (3); }}
1. The static variable of the parent class, traced back, finds the static variable of the top-level parent class, and then initializes it down to the current class.
2, enter the current class construction method, the first sentence of the construction method is to call the constructor of the parent class, upstream, to find the top-level parent class, first initialize the parent class instance variable, and then execute the parent class construction method inside the statement, so go down into the current class, and then initialize the current class instance variable, Executes the statement after the parent class constructor method is called in the current class construction method.
(not to be continued)
Java Initialization Order