First look at a code
Parent Class Code:
1 Public classParent {2 3 {4SYSTEM.OUT.PRINTLN ("Parent non-static code block"); 5 }6 7 Static {8SYSTEM.OUT.PRINTLN ("Parent Static code block");9 }Ten One PublicString name; A - - PublicParent () { the This. Name = "Xiaoming"; - //play1 (); - play (); - } + - //Public void Play1 () { + //System.out.println (name + "Play the game in the parent Class!!! "); A // } at - Public voidPlay () { -SYSTEM.OUT.PRINTLN (name + "Play the game in the parent Class!!! "); - } -}
Sub-class Code:
1 Public classSubextendsparent{2 3 {4SYSTEM.OUT.PRINTLN ("Sub non-static code block"); 5 }6 7 Static {8System.out.println ("Sub Static code block");9 }Ten One PublicString name; A - PublicSub (String name) { - Super(); the This. Name =name; - } - - Public voidPlay () { +SYSTEM.OUT.PRINTLN (name + "Play the game in sub Class!!!" "); - } +}
Main Method Code:
1 Public classMain {2 3 Public Static voidMain (string[] args) {4 5 //System.out.println ("======== Main method ========");6 7Sub Sub =NewSub ("Xiao Qiang");8 9 Sub.play ();Ten One A } -
The result of the operation is: parent static code block
Sub Static code block
Parent non-static code block
Null play the game in the Sub Class!!!
Sub non-static code block
Xiao Qiang plays the game in sub Class!!!
There are several points to note:
(1) The reason for the output null is that the name has not been initialized at that time (Sub.name)
(2) while play () runs out of sub because there is no parent object
Summary:The inheritance structure runs in memory steps:Static variables of the parent class and static program blocks---the static variables of the subclass and static program blocks---(subclass Main method)---Parent class non-static code block---Parent class initialization---The constructor method in the parent class---subclass the non-static code block---Subclass initialization---Subclass constructor method---object invocation The method
java--Run order of inheritance