当new()发生时,代码初始化顺序
首先给出要验证的结论:
一、当有static修饰的静态代码时
父类静态代码块(同类内static修饰的属性按顺序执行)>子类静态代码块(同类内static修饰的成员按顺序执行)>父类属性、代码块(按声明顺序执行) >父类构造器> 子类属性、代码块(按声明顺序执行)>子类构造器
二、当没有static修饰的静态代码时
父类属性、代码块(按声明顺序执行) >父类构造器> 子类属性、代码块(按声明顺序执行)>子类构造器
验证一、
class Family { Family (Class className) { System.out.println("创建Family对象"); System.out.println(className.getName()); } } class Person { Person() { System.out.println("创建Person对象"); } public static Family family = new Family(Person.class); static { System.out.println("执行Person静态代码块"); } { System.out.println("执行Person代码块"); } } public class Student extends Person { public Student() { System.out.println("创建student对象"); } { System.out.println("执行Student代码块"); } static { System.out.println("执行Student静态代码块"); } public static Family staticFamily = new Family(Student.class); @Test public void test() { System.out.println("============="); } public Family family = new Family(Student.class); } 执行结果: 创建Family对象 com.tca.thinkInJava.chap7.Person 执行Person静态代码块 执行Student静态代码块 创建Family对象 com.tca.thinkInJava.chap7.Student 执行Person代码块 创建Person对象 执行Student代码块 创建Family对象 com.tca.thinkInJava.chap7.Student 创建student对象
验证二、
//建筑 class Building { public Building() { System.out.println("Building"); } } //房子 class House extends Building{ public LivingRoom livingRoom = new LivingRoom();//卧室 public House() { System.out.println("House"); } } //别墅 class Villa extends House{ public Villa () { System.out.println("Villa"); } } //卧室 class LivingRoom { public Bed bedFirst = new Bed();//床 public Desk deskFirst = new Desk();//桌子 public LivingRoom () { System.out.println("LivingRoom"); } } //床 class Bed { public Bed () { System.out.println("Bed"); } } //桌子 class Desk { public Desk () { System.out.println("Desk"); } } 此时,我们new Villa(): public class InitializeDemo { @Test public void testInitialize() { Villa villa = new Villa(); } } 执行结果为: Building Bed Desk LivingRoom House Villa