java中对于有继承关系的加载顺序

父类:
public class A {
private int i = print("this is a common variable");
private static int j = print("this is a static common variable");
public A(){
System.out.println("this is a construct");
}

static {
System.out.println("this is a static");
}

{
System.out.println("this is a non static");
}
static int print(String str){
System.out.println(str);
return 2;
}

}

字类:
public class B extends A{
private int i = print("this is b common variable");
private static int j = print("this is b static common variable");
public B(){
System.out.println("this is b construct");
}

static {
System.out.println("this is b static");
}

{
System.out.println("this is b non static");
}

public static void main(String[] args) {
A b=new B();
}
}

输出结果:

this is a static common variable
this is a static
this is b static common variable
this is b static
this is a common variable
this is a non static
this is a construct
this is b common variable
this is b non static
this is b construct

最后得出类加载顺序为:先按照声明顺序初始化基类静态变量和静态代码块,接着按照声明顺序初始化子类静态变量和静态代码块,而后按照声明顺序初始化基类普通变量和普通代码块,然后执行基类构造函数,接着按照声明顺序初始化子类普通变量和普通代码块,最后执行子类构造函数。

posted @ 2020-11-09 10:47  IAmSao瑞  阅读(87)  评论(0)    收藏  举报