JAVA执行顺序如下:
1.首先加载所有类中调到的class。
2.先加载父类,再加载子类。
3.加载过程中,会执行静态代码块。
4.new Constructor()的时候会先执行 代码块{},再执行 Constuctor();
5.静态变量在加载过程中赋值,与静态代码块是从上到下的执行顺序。
所以输出结果为:
1.父类静态代码块。
2.子类静态代码块。
3.父类 代码块。
4.父类构造函数。
5.子类代码块。
6.子类构造函数。
1 package test_static; 2 3 public class Fathor { 4 public String name="fathor"; 5 public static String sex="man"; 6 7 { 8 System.out.println("this is fathor's 代码块!"); 9 } 10 11 static{ 12 sex="male"; 13 System.out.println("this is fathor's 静态代码块!"); 14 } 15 16 public Fathor() { 17 System.out.println("Fathor'sex is :"+sex); 18 System.out.println("this is Fathor's Constructor"); 19 } 20 }
1 package test_static; 2 3 public class Son extends Fathor{ 4 public String name = "son"; 5 6 public static String sex="man"; 7 8 { 9 System.out.println("this is son's 代码块!"); 10 } 11 12 static{ 13 sex="male"; 14 System.out.println("this is son's 静态代码块!"); 15 } 16 17 public Son() { 18 System.out.println("this is son's Constructor"); 19 System.out.println("son sex is "+sex); 20 } 21 }
1 package test_static; 2 3 public class Test { 4 public static void main(String[] args) { 5 Son s = new Son(); 6 } 7 }
执行结果:
1 this is fathor's 静态代码块! 2 this is son's 静态代码块! 3 this is fathor's 代码块! 4 Fathor'sex is :male 5 this is Fathor's Constructor 6 this is son's 代码块! 7 this is son's Constructor 8 son sex is male