[@more@]
class Egg2 {
static int i=5;
int j=5;
static//父类静态变量初始化块首先被执行,在main方法之前。
{
System.out.println("superClass static block initialized ");
}
protected class Yolk {
public Yolk() {
System.out.println("Egg2.Yolk()");
}
public void f() {
System.out.println("call method f() in superClass");
}
private void m() {
System.out.println("call method m() in superClass");
}
}
private Yolk y = new Yolk();//y是Yolk的对象同时是Egg2的成员
{ //非静态变量语句块,在静态语句块之后,main方法之后,构造方法之前执行
System.out.println("superClass member block initialized");
}
public Egg2() {
System.out.println("New Egg2()");//2
System.out.println("Egg2`s constructor initialized");
}
public void insertYolk(Yolk yy) {
y = yy;
}
public void g() {
y.f();
y.m();
}
private void n() {
System.out.println("method n() in superClass");
}
}
public class BigEgg2 extends Egg2 {
static int i;
int j=10;
static //子类静态初始化块在父类静态初始化块后执行,在main方法之前。
{
System.out.println("subClass static block initialized");
}
{ //子类的非静态初始化块
Yolk subY =new Yolk();
System.out.println("subClass member block initialized");
}
public class Yolk extends Egg2.Yolk {
public Yolk() {
System.out.println("BigEgg2.Yolk()");
}
public void f() {
System.out.println("invoke method f() in subClass");
}
public void m() {
System.out.println("invoke method m() in subClass");
}
}
public BigEgg2() {
System.out.println("begin new Yolk() in BigEgg2`s constructor");
insertYolk(new Yolk());
}
public void n() {
System.out.println("method n() in subClass");
}
public static void main(String[] args) {
System.out.println("main begins!");
System.out.println("-------------------------------");
Egg2 e2 = new BigEgg2();
e2.g();
//e2.n(); error! 因为父类的n方法是private的,所以无法在此访问
System.out.println("e2.i= "+e2.i);
System.out.println("e2.j= "+e2.j);
System.out.println("-------------------------------");
BigEgg2 ee=new BigEgg2();
ee.g();
ee.n();
System.out.println("ee.i= "+ee.i);
System.out.println("ee.j= "+ee.j);
System.out.println("i = "+i);
}
}
初始化顺序:父类静态初始化→子类静态初始化(在main方法之前)→子类创建对象后→
父类的非静态变量初始化→父类的构造方法初始化→子类的非静态变量初始化→子类的构造方法初始化。
静态初始化与非静态初始化顺序:按照语句顺序逐一进行