上星期去面试的时候,被问了一条关于java初始化顺序的问题,由于太久没看过core java方面的基础知识,所以不是很记得,只能大概地说了一下。之后,写了一个demo来重新补漏,希望借此能使我以后永远记住。
先定义一个Person类
public class Person {
public Person(){
System.out.println("Person non-param constructor!");
}
public Person(String s){
System.out.println(s);
}
}
一、无继承版
public class Base {
private static Person pserson1 = new Person("person1 initializes!");
private Person person2 = new Person("person2 initializes!");
public Base() {
System.out.println("Base non-param constructor");
}
private static Person person3 = new Person("person3 initializes!");
static {
System.out.println("static block!");
}
public static void main(String[] args) {
Base base = new Base();
}
}
控制台输出结果
结论
1、静态变量、静态块(按代码中static定义的顺序初始化)
2、实例变量
3、构造器
二、继承版
public class Base {
private static Person pserson1 = new Person("Base person1 initializes!");
private Person person2 = new Person("Base person2 initializes!");
public Base() {
System.out.println("Base non-param constructor");
}
private static Person person3 = new Person("Base person3 initializes!");
static {
System.out.println("Base static block!");
}
}
public class Derived extends Base{
private static Person person1 = new Person("Derived person1 initializes!");
private Person person2 = new Person("Derived person2 initializes!");
static {
System.out.println("Derived static block!");
}
public Derived() {
System.out.println("Derived constructor!");
}
public static void main(String[] args) {
Derived derived = new Derived();
}
}
结论:
- 父类static(按static定义顺序)
- 子类static(按static定义顺序)
- 父类实例变量
- 父类构造器
- 子类实例变量
- 子类构造器