继承时候类的执行顺序问题
public class Parent
{
//1
static int a = 1;
//2
static
{
a = 10;
System.out.println("parent static code");
}
//4
public Parent()
{
System.out.println("Parent constructor");
System.out.println("Parent a=" + a);
}
public static void main(String[] args)
{
System.out.println("***************");
Parent c = new Child();
}
}
class Child extends Parent
{
static int a = 2;
//3
static
{
a = 20;
System.out.println("child static code");
}
//5
public Child()
{
System.out.println("Child constructor");
System.out.println("Child var a=" + a);
}
}
输出结果:
parent static
code
child static code
***************
Parent constructor
Parent a =10
Child constructor
Child var a =20
child static code
***************
Parent constructor
Parent a =10
Child constructor
Child var a =20
结论:
在还没有实例化类的时候 已经执行了static代码块。
顺序是先父类后子类.
然后才调用父类的构造方法,再调用子类的构造方法