(a) Why must the constructor of the parent class be called before the constructor of the subclass is run? Can you turn around? Why can't it be reversed?
Answer: Java automatically inserts the base class constructor in the derived class constructor, for example
classa {a () {System. out. println ("A Constructor"); } } classB {B () {System. out. println ("B Constructor"); } } Public classC extends A {b b=NewB (); Public Static voidMain (string[] args) {c C=NewC (); } }
So, is it possible to assume that the base class constructor call is the first statement of the derived class constructor, so that it is called when the constructor of the derived class is called?
However, the result is: A constructor B Constructor
This shows that the initialization of the base class occurs before the initialization of the derived class (including automatic initialization, constructors, and so on) . , but when there is no parameter
(b) Calling the base class construction method through super, must be the first statement in the subclass construction method. When calling a constructor with "parameters" in the base class
Class Grandparent {public grandparent () { System.out.println ("Grandparent Created."); Public grandparent (String string) { System.out.println ("Grandparent created.string:" + String);} } Class Parent extends Grandparent {public parent () { super ("hello.grandparent."); System.out.println ("Parent Created"); Super ("hello.grandparent.");} } Class Child extends the Parent {public Child () { System.out.println ("Child Created");} }
But the result grandparent Created.String:Hello.Grandparent. (parameter)
Parent Created
Child created although you Spuer ("Hello.grandparent") is located in the first sentence of the derived class, in a word, the compiler finds the default constructor of the base class without explicitly invoking the base class constructor, finds an error, and joins the call to it. The base class has no default constructor and must be called explicitly. Initialization of a base class occurs before the initialization of a derived class (including automatic initialization, constructors, and so on).
Construction method invocation under inheritance conditions