(1)如果只有一个类,执行顺序:
静态初始化代码块、构造代码块、构造方法
代码举例:
public class HelloB {
public HelloB() {
System.out.println("B构造方法");
}
{
System.out.println("B构造代码块");
}
static {
System.out.println("B static");
}
public static void main(String[] args) {
new HelloB();
}
}
运行结果:
(2)如果有父类和子类,执行顺序:
1.父类静态初始化代码块、子类静态初始化代码块
2.父类构造代码块、父类构造方法
3.子类构造代码块、子类构造方法
代码举例:
public class HelloB extends HelloA {
public HelloB() {
System.out.println("B构造方法");
}
{
System.out.println("B构造代码块");
}
static {
System.out.println("B static");
}
public static void main(String[] args) {
new HelloB();
}
}
class HelloA {
public HelloA() {
System.out.println("A构造方法");
}
{
System.out.println("A构造代码块");
}
static {
System.out.println("A static");
}
}
运行结果: