JAVA类的实例化顺序
JAVA类的实例化顺序
代码
class Fatherstatic{
public Fatherstatic(){
System.out.println("father静态变量");
}
}
class Childstatic{
public Childstatic(){
System.out.println("child静态变量");
}
}
class Father_not_static{
public Father_not_static(){
System.out.println("father 非静态变量");
}
}
class Child_not_static{
public Child_not_static(){
System.out.println("child 非静态变量");
}
}
class Father {
static Fatherstatic fatherstatic = new Fatherstatic();
Father_not_static father_not_static = new Father_not_static();
static {
System.out.println("Father静态代码块");
}
{
System.out.println("Father动态代码块");
}
public Father(){
System.out.println("Father构造器");
}
}
class Child extends Father {
static Childstatic childstatic = new Childstatic();
Child_not_static child_not_static = new Child_not_static();
static {
System.out.println("Child静态代码块");
}
{
System.out.println("Child动态代码块");
}
public Child(){
System.out.println("Child构造器");
}
public static void main(String[] args) {
new Child();
}
}
运行结果
father静态变量
Father静态代码块
child静态变量
Child静态代码块
father 非静态变量
Father动态代码块
Father构造器
child 非静态变量
Child动态代码块
Child构造器
Process finished with exit code 0
总结
初始化顺序如下:
-
父类静态变量
-
父类静态代码块
-
子类静态变量
-
子类静态代码块
-
父类非静态变量(父类实例成员变量)
-
父类动态代码块
-
父类构造函数
-
子类非静态变量(子类实例成员变量)
-
子类动态代码块
-
子类构造函数