java类中各成员初始化的顺序
class Father { static{ System. out.println("父类静态代码块初始化" ); } { System. out.println("父类代码块初始化" ); } private static String s=print(); public static String print() { System. out.println("父类静态方法" ); return "父类静态成员变量的初始化" ; } public Father() { System. out.println("父类无参构造函数初始化完成" ); show(); } public void show() { System. out.println("父类show()方法" ); } } class Son extends Father { static{ System. out.println("子类静态代码块初始化" ); } { System. out.println("子类代码块初始化" ); } private static int i=1; private String s="子类私有成员变量" ; public void show() { System. out.println("子类show()方法:i=" +i); } public Son() { System. out.println("子类构造函数初始化完成" ); show(); } } public class TestClassLoadSeq { public static void main(String[] args) { new Son(); } }
输出结果:
1 class Father 2 { 3 private static String s= print(); 4 5 static{ 6 System. out.println("父类静态代码块初始化" ); 7 } 8 { 9 System. out.println("父类代码块初始化" ); 10 } 11 public static String print() 12 { 13 System. out.println("父类静态方法" ); 14 return "父类静态成员变量的初始化" ; 15 } 16 public Father() 17 { 18 System. out.println("父类无参构造函数初始化完成" ); 19 show(); 20 } 21 public void show() 22 { 23 System. out.println("父类show()方法" ); 24 } 25 } 26 class Son extends Father 27 { 28 static{ 29 System. out.println("子类静态代码块初始化" ); 30 } 31 { 32 System. out.println("子类代码块初始化" ); 33 } 34 private int i =1; 35 private String s="子类私有成员变量" ; 36 public void show() 37 { 38 System. out.println("子类show()方法:i=" +i); 39 } 40 public Son() 41 { 42 System. out.println("子类构造函数初始化完成" ); 43 System. out.println("子类成员变量初始化完成:s=" +s); 44 show(); 45 } 46 } 47 public class TestClassLoadSeq { 48 public static void main(String[] args) 49 { 50 new Son(); 51 } 52 53 } 54
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。