Subclass inherits the call sequence of the methods of the parent class and the call sequence of the class.
To understand the execution sequence of each code block in the parent class and subclass when a subclass inherits the parent class and calls a method of the subclass
We create a Parent class Parent and a Child sub-class by ourselves. The Code is as follows:
Parent code:
1 package ParentAndChild; 2 3 public class Parent {4 static {5 System. out. println ("parent static code block"); 6} 7 8 {9 System. out. println ("Parent common code block"); 10} 11 12 public Parent () {13 super (); 14 System. out. println ("parent class constructor method"); 15} 16 17 public void A () {18 System. out. println ("parent class A method"); 19} 20 21}
Subclass code:
Package ParentAndChild; public class Child extends Parent {static {System. out. println ("subclass static code block");} {System. out. println ("subclass common code block");} public Child () {super (); System. out. println ("subclass constructor method");} public void A () {System. out. println ("subclass A method");} public static void main (String [] args) {Child child = new Child (); child. A ();}}
Output result:
Conclusion:When a subclass inherits the parent class and calls a method of the subclass, the execution sequence of the code block is
1) Static code block of the parent class
2) subclass static code block
3) common code block of the parent class
4) parent class constructor Method
5) subclass common code block
6) subclass constructor Method
7) subclass A Method