Run the Testinherits.java sample, observe the output, notice that the call relationship between the parent class and the subclass constructs a method to modify the code of the parents constructor method, explicitly call the other constructor of grandparent, notice whether the calling code is the first sentence, the impact is significant!
Program:
classGrandparent { Publicgrandparent () {System.out.println ("Grandparent Created."); } Publicgrandparent (String string) {System.out.println ("Grandparent created.string:" +string); }} classParentextendsgrandparent{ PublicParent () {//super ("hello.grandparent.");System.out.println ("Parent Created"); //super ("hello.grandparent."); }}classChildextendsParent { PublicChild () {System.out.println ("Child Created"); }} Public classTestinherits { Public Static voidMain (String args[]) {child C=NewChild (); }}
Results:
1 Original Program
2 super in the first sentence
3 Super Not in the first sentence
Conclusion:
through
Super
called
base class construction method
, it must be
sub-class construction methods
in
the first statement. Thinking
Why do I have to call the construction method of the parent class before the constructor of the subclass is run? Can you turn around? Why can't it be reversed?
because the initialization of a subclass causes the execution of the parent class constructor. The parent class inherits the grandparent class, and the child class inherits the parent class, because Super is in the parent class and calls its base class grandparent constructor, because super ("hello.grandparent.") With a parameter, the second constructor is called.
Construct method call Super under inheritance condition