Java中不同类型代码是由严格的执行顺序的。
对于一个没有继承派生关系的类来说,它的代码执行顺序是这样的:
静态成员变量,静态代码块(两者以定义顺序来执行),成员变量,代码块,构造函数,成员函数。
如果有继承关系,那么子类中的调用顺序如下:
父类(静态成员变量,静态代码块),子类(静态成员变量,静态代码块),父类(成员变量,代码块),父类构造函数,子类(成员变量,代码块),子类构造函数。
请看下面两个类的声明。
父类:
public class Parent {
final static int x = 0;
final static int y;
final int z;
static {
System.out.println("Parent Static code");
y = 5;
//z = 6; //Cannot make a static reference to the non-static field z
}
final int a;
{
System.out.println("Parent Dynamic code");
a = 3;
b = 4;
//System.out.println("b = " + b); //Cannot reference a field before it is defined
}
final int b;
//final static int c; //The blank final field c may not have been initialized
public Parent() {
z = 6;
//c = 6; //The final field Parent.c cannot be assigned
System.out.println("Parent Constructor code");
}
public void method() {
System.out.println("Parent method");
}
}
子类:
public class Son extends Parent {
int sX;
final int sY;
static final int sZ;
{
sX = 1;
sY = 2;
System.out.println(sX);
System.out.println(sY);
System.out.println("Son Dynamic model 1");
}
static {
sZ = 1;
System.out.println(sZ);
//System.out.println(sC);
System.out.println("Son Static model 1");
}
int sA = 0;
final int sB = 1;
static final int sC = 2;
int sD;
final int sE;
static final int sF;
{
sE = 3;
System.out.println(sE);
System.out.println("Son Dynamic model 2");
}
static {
sF = 1;
System.out.println(sF);
//System.out.println(sC);
System.out.println("Son Static model 2");
}
int sH;
final int sI;
static int sJ;
public Son() {
sH = 3;
sI = 4;
sJ = 6;
System.out.println("Son constructor");
}
public void method() {
System.out.println("Son method");
}
}
假设在调用函数中有如下代码:
Parent p1 = new Son();
p1.method();
Parent p2 = new Parent();
p2.method();
Son s1 = new Son();
s1.method();
其执行输出如下:
Parent Static code
1
Son Static model 1
1
Son Static model 2
Parent Dynamic code
Parent Constructor code
1
2
Son Dynamic model 1
3
Son Dynamic model 2
Son constructor
Son method
Parent Dynamic code
Parent Constructor code
Parent method
Parent Dynamic code
Parent Constructor code
1
2
Son Dynamic model 1
3
Son Dynamic model 2
Son constructor
Son method