Let me talk about the conclusion first: static code block === > ordinary code block === > construction method
description: static code block will only be executed once when the class is loaded into memory, and the other two will be executed once every time new
public class Test{
//静态代码快
static {
System.out.println("A");
}
//普通代码快
{
System.out.println("B");
}
//构造方法
Test(){
System.out.println("C");
}
public static void main(String[] args) {
System.out.println("D");
new Test();
new Test();
}
}
The output is:
A
D
B
C
B
C
++++++++++++++++++++++++++++++++++++ dividing line++++++++++++++ ++++++++++++++++++++++
If Test inherits a class at this time, does the echo load the subclass or the parent class?
class Person{
Person(){
System.out.println("E");
}
}
public class Test{
//静态代码快
static {
System.out.println("A");
}
//普通代码快
{
System.out.println("B");
}
//构造方法
Test(){
System.out.println("C");
}
public static void main(String[] args) {
System.out.println("D");
new Test();
new Test();
}
}
The output is:
A
D
E
B
C
E
B
C
So when the class is loaded, the parent class will be loaded first.