JAVA Parent-Child class constructor, static code block, and other execution sequence
Recently, I encountered a Java constructor when I was working on the project, and I learned some execution sequence knowledge about code blocks. I just ran an experiment on it. When subclass A inherits the parent class B
A a = new A();
In this case, what is the sequence of the static code blocks and constructor executions of the parent class and subclass?
My conclusion is:
Parent Class B static code block-> subclass A static code block-> parent class B non-static code block-> parent class B constructor-> subclass A non-static code block-> subclass A constructor
See the code below:
Public class Parent {public Parent () {System. out. println (parent constructor method);} static {System. out. println (parent static code);} // non-static code block {System. out. println (parent nonStatic code );}}
Public class Children extends Parent {public Children () {System. out. println (children constructor code);} static {System. out. println (children static code);} // non-static code block {System. out. println (children nonStatic code);} public static void main (String [] args) {Children c = new Children ();}}
Output result:
The code is not difficult. It is particularly noted that the static code block of the subclass in the output result follows the static code block of the parent class. In this case, you should pay special attention to it.