标签:
子类的实例化主要分为两个步骤:
<1>.类相关静态内容 初始化;
*先父类再子类:
1.父类的static属性;
2.父类的static块;
3.子类的static属性;
4.子类的static块;
<2>.类的实例内容 初始化;
*调用构造子:先父类后子类:构造子调用之前先实例化实例字段和块
5.父类的普通属性;
6.父类的普通块;
7.父类的构造子;
8.子类的普通属性;
9.子类的普通块;
10.子类的构造子;
1 public class ClzInit { 2 public static void main(String[] args) { 3 new Son(); 4 } 5 } 6 7 class Parent { 8 protected int n = 5; 9 protected static int m = 5; 10 11 static { 12 m = m * 2; 13 System.out.println("父类静态块调用; m=" + m); 14 } 15 16 { 17 n = n * 2; 18 m = m * 2; 19 System.out.print("父类普通块调用; "); 20 System.out.print("n=" + n); 21 System.out.println(" m=" + m); 22 } 23 24 public Parent() { 25 this.n = n * 10; 26 m = m + 10; 27 System.out.print("父类构造子; n=" + n); 28 System.out.println(" m=" + m); 29 } 30 } 31 32 class Son extends Parent { 33 private int sn = 3; 34 private static int sm = 3; 35 36 static { 37 m = m + 2; 38 sm = sm + 2; 39 System.out.println("子类静态块调用; m=" + m); 40 } 41 42 { 43 n = n + 2; 44 sn = sn + 2; 45 m = m + 2; 46 System.out.print("子类普通块调用; "); 47 System.out.print("n=" + n); 48 System.out.print(" sn=" + sn); 49 System.out.println(" m=" + m); 50 } 51 52 public Son() { 53 this.n = n + 10; 54 sn = sn + 10; 55 m = m + 10; 56 System.out.print("子类构造子; n=" + n); 57 System.out.println(" m=" + m); 58 } 59 }
运行结果:
父类静态块调用; m=10 子类静态块调用; m=12 父类普通块调用; n=10 m=24 父类构造子; n=100 m=34 子类普通块调用; n=102 sn=5 m=36 子类构造子; n=112 m=46
此外,如果子类重写了父类的方法,而父类的静态属性、静态块、普通属性或者普通块中含有此同名方法,则实际调用的是子类重写后的方法而非父类原本的方法,虽然发生在父类顺序阶段。
如下:
public class Main { public static void main(String[] args) { new Son1(); } } class Father1 { int k = foo(); static { System.out.println("father static block"); } public Father1() { System.out.println("father constructor"); } public int foo() { System.out.println("father initializing"); return 1; } } class Son1 extends Father1 { int k1 = foo(); static { System.out.println("son static"); } public Son1() { System.out.println("son constructor"); } public int foo() { System.out.println("son initializing"); return 1; } }
运行结果:
father static block son static son initializing father constructor son initializing son constructor
注意黑体字那行,其顺序为执行父类普通属性极端,但由于涉及的方法在子类重写,实际上调用了子类重写后的方法。
标签:
原文地址:http://www.cnblogs.com/chen0958/p/4865628.html