问题引入
一直对这个问题有了解,也会涉及到类似的问题。刚好有空便测试一把,作为记录。
测试代码
新建Student与Person类,Student继承Person类。
public class Person {
private String name;
private Integer age;
private Boolean sex;
private static final String STATIC_FINAL_PARAM = getStaticFinalParam();
private static String STATIC_PARAM = getStaticParam();
private static String getStaticParam() {
System.out.println("Father StaticParam");
return "Father StaticParam";
}
private static String getStaticFinalParam() {
System.out.println("Father StaticFinalParam");
return "Father StaticFinalParam";
}
public Person() {
System.out.println("Father Constructor");
}
static {
System.out.println("father static code block");
}
{
System.out.println("father code block");
}
// 省略getter、setter、toString
}
public class Student extends Person {
private String studentNumber;
private String School;
private static final String STATIC_FINAL_PARAM = getStaticFinalParam();
private static String STATIC_PARAM = getStaticParam();
private static String getStaticParam() {
System.out.println("Child StaticParam");
return "Child StaticParam";
}
private static String getStaticFinalParam() {
System.out.println("Child StaticFinalParam");
return "Child StaticFinalParam";
}
public Student() {
System.out.println("Child Constructor");
}
static {
System.out.println("child static code block");
}
{
System.out.println("child code block");
}
public void sayHello() {
System.out.println("Hello,I'm chenwb!");
}
public static void main(String[] args) {
Student student = new Student();
student.sayHello();
}
}
执行Student类的main方法:
Father StaticFinalParam
Father StaticParam
father static code block
Child StaticFinalParam
Child StaticParam
child static code block
father code block
Father Constructor
child code block
Child Constructor
Hello,I’m chenwb!
结果分析
1、首先加载父类,加载工程中先初始化static final变量,再初始化static变量,再执行静态代码块
Father StaticFinalParam
Father StaticParam
father static code block
2、然后加载子类,也是同样的顺序
Child StaticFinalParam
Child StaticParam
child static code block
3、开始对象实例化,先执行父类的普通代码块,再是构造方法
father code block
Father Constructor
4、 然后是子类普通代码块,子类构造方法
child code block
Child Constructor
5、执行后续代码
Hello,I’m chenwb!