1 public class F { 2 static { 3 System.out.println("f static"); 4 } 5 6 private static int a = me(); 7 8 private static int me() { 9 System.out.println("f static field"); 10 return 1; 11 } 12 13 public F() { 14 System.out.println("f cons"); 15 } 16 } 17 18 --- 19 public class S extends F { 20 static { 21 System.out.println("s static"); 22 } 23 24 private static int s = mew(); 25 26 private static int mew() { 27 System.out.println("s static field"); 28 return 0; 29 } 30 31 32 public S() { 33 System.out.println("s cons"); 34 } 35 36 public static void main(String[] args) { 37 System.out.println("a main"); 38 S s = new S(); 39 } 40 }
执行结果
f static f static field s static s static field a main f cons s cons
类在加载的时候先执行静态部分的代码,先执行静态代码块还是静态字段 需要根据顺序来执行,谁排前边谁先执行