Theme NexT works best with JavaScript enabled
0%

构造顺序

^ _ ^

Q & A

类的实例化顺序,比如父类静态数据,构造函数,字段,子类静态数据,构造函数,字段,当new的时候,他们的执行顺序。

  1. 父类静态数据
  2. 子类静态数据
  3. 父类普通变量
  4. 父类构造函数
  5. 子类普通变量
  6. 子类构造函数

测试代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class InitA{
public InitA(String host){
System.out.println(host + ":A constructed.");
}
}
class B{
public B(String host) {
System.out.println(host + ":B constructed.");
}
}
class Parent{
public InitA a = new InitA("Parent");
public static B b = new B("Parent");
public Parent() {
System.out.println("Parent constructed.");
}
}
class Son extends Parent{
public static InitA a = new InitA("Son");
public B b = new B("Son");
public Son() {
System.out.println("Son constructed.");
}
}
public class InitialOrderTest {
public static void main(String[] args) {
Son demo = new Son();
}
}