Java子类父类的各个类执行顺序

正确的执行顺序是:

父类B静态代码块->子类A静态代码块->
父类B非静态代码块->父类B构造函数->
子类A非静态代码块->子类A构造函数

也就是说非静态初始化块的执行顺序要在构造函数之前。

class SuperClass{
private static String STR = "Super
Class Static Variable";
static{

System.out.println("Super Class Static Block:"+STR);
}

public SuperClass() {
System.out.println("Super Class
Constructor Method");
}
{

System.out.println("Super Class Block");
}

}
public class ObjectInit extends SuperClass{
private
static String STR = "Class Static Variable";
static{

System.out.println("Class Static Block:"+STR);
}

public ObjectInit() {
System.out.println("Constructor
Method");
}
{
System.out.println("Class
Block");
}
public static void main(String[] args) {

@SuppressWarnings("unused")
ObjectInit a =new
ObjectInit();
}
}

执行完之后可以看到顺序如下:
Super Class Static Block:Super Class Static Variable
Class
Static Block:Class Static Variable

Super Class Block

Super Class Constructor Method

Class Block

Constructor Method

你可能感兴趣的:(Java)