Java 类的构造器、静态代码块、静态方法执行顺序

时间:2022-05-15 19:37:24
public class Husband extends Persona{
/**第二执行
public Husband() {
super("One");
System.out.println("Two");
}
}

public class Wife extends Persona {
/**第三执行
public Wife(){
super("Four");
}
/**第四执行
public Wife(String name) {
super(name);
System.out.println("Three");
}
}

public class Persona {
private String name;
private String sex;
private Integer age;

public Persona(String name){
System.out.println("我的名字是:"+ name);
}
/**省略Seter/getter


public class Test {
/**
* 静态块只执行一次/最先执行的
*/
static {
System.out.println("Here We Go");
}
/**第五执行
public Test(){
System.out.println("This just a test");
}
public static void main(String[] args) {
Husband husband=new Husband();
Wife wife=new Wife();
wife=new Wife("Five");
Test test=new Test();
test.say();

}
/**最后执行
public static void say(){
System.out.println("Say Something");
}
}



输出结果:  

Here We Go

我的名字是:One

Two

我的名字是:Four

我的名字是:Five

Three

This just a test

Say Something