Example source: Ideas for Java Programming, blog link: Notes on Chapters 1-15 of Ideas for Java programming
Case code:
class A{
public A(a)
{
System.out.println("1. Constructor of parent CLASS A");
}
{
System.out.println("2. Construct code block of parent class A");
}
static{
System.out.println("3. Static code block for parent CLASS A"); }}public class B extends A{
public B(a)
{
System.out.println("4. Constructor of subclass B");
}
{
System.out.println("5. Construct code block for subclass B");
}
static{
System.out.println("6. Static code block for subclass B");
}
/ / test
public static void main(String[] args)
{
System.out.println("7.start......");
new B();
System.out.println("8.end....."); }}Copy the code
Output result:
>>> 3.Static code block for parent CLASS A >>>6.Static code block for subclass B >>>7.start......
>>> 2.Constructor code block for parent CLASS A >>>1.Constructor of parent class A >>>5.Subclass B construct code block >>>4.Subclass B >>>8.end.....
Copy the code
- Static block of main class B is executed before the main method, so 6 should be executed before 7, and class B inherits from class A, so static block 3 of class A is executed first, so the execution sequence before entering the main method is: 3 and 6
- After entering the main method, execute 7,
new B()
Should be performed after A construction method and the structure of the B method, but as A result of both class A and class B construction activity code, structure code blocks and takes precedence over method performs the 2 1 (A) the structure of the family 5 4 (B) the structure of the family, how many objects, construct family is executed several times, have two objects in the title soThe execution sequence is 3 6 7 2 1 5 4 2 1 5 4 8
Here’s a more specific example: an interesting “initialization” interview question