A. First pasting the code
public class InitOrderDemo extends Father {
private PObject p = new PObject("子类 - 实例变量");
static {
sp = new PObject("子类静态代码块 - 静态变量");
}
static PObject sp = new PObject("子类 - 静态变量");
InitOrderDemo(){
System.out.println("子类构造函数开始执行 ...");
}
public static void main(String[] args) {
new InitOrderDemo();
}
}
class Father{
private PObject p = new PObject("父类 - 实例变量");
private static PObject sp = new PObject("父类 - 静态变量");
Father(){
System.out.println("父类构造函数开始执行 ...");
}
{
p = new PObject("父类实例代码块 - 实例变量");
}
static {
sp = new PObject("父类静态代码块 - 静态变量");
}
}
class PObject{
PObject(String type){
System.out.println("作为 "+type+" 成员的 PObject 构造函数执行 ...");
}
}
II. The results run routine
作为 父类 - 静态变量 成员的 PObject 构造函数执行 ...
作为 父类静态代码块 - 静态变量 成员的 PObject 构造函数执行 ...
作为 子类静态代码块 - 静态变量 成员的 PObject 构造函数执行 ...
作为 子类 - 静态变量 成员的 PObject 构造函数执行 ...
作为 父类 - 实例变量 成员的 PObject 构造函数执行 ...
作为 父类实例代码块 - 实例变量 成员的 PObject 构造函数执行 ...
父类构造函数开始执行 ...
作为 子类 - 实例变量 成员的 PObject 构造函数执行 ...
子类构造函数开始执行 ...
III. Summary
Sentence: 先静态,后实例。先父类,后子类。
this order:
- If there is no inheritance, initialize static part, after initializing the Examples section
- If there is inheritance:
- Fathers class static part, the static portion of the subclasses
- Fathers class instances portion, the parent class constructor
- First portion subclass instance, the subclass Constructors
- Supplementary part:
- Static portion sequentially performed according to the class, and the static block of code can reference static member variables in advance defined below
- Examples of moieties (including instance variables and instance code blocks) are always performed sequentially before the constructor, not in the order in the class