继承时候类的执行顺序问题,一般都是选择题,问你将会打印出什么?
package
com.test;

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
由此可看出在还没有实例化类的时候(注意*号)已经执行了static代码块。
顺序是先父类后子类.
然后才调用父类的构造方法,再调用子类的构造方法.就是这个顺序了.
package
com.test;

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);
}
}


























































输出结果:








由此可看出在还没有实例化类的时候(注意*号)已经执行了static代码块。
顺序是先父类后子类.
然后才调用父类的构造方法,再调用子类的构造方法.就是这个顺序了.


























































