sandwich

java中构造器的调用顺序

人走茶凉 提交于 2020-01-16 00:36:21
在编程的过程中,我们经常会遇到多个类的继承问题,那么多个类的构造器是按照什么顺序调用的呢? 先看一段代码: 1 public class Meal { 2 public Meal() { 3 System.out.println("meal constructor() "); 4 } 5 } 6 7 public class Bread { 8 public Bread() { 9 System.out.println("bread constructor() "); 10 } 11 } 12 13 public class Cheese { 14 public Cheese() { 15 System.out.println("cheese constructor() "); 16 } 17 } 18 19 public class Lettuce { 20 public Lettuce() { 21 System.out.println("Lettuce constructor() "); 22 } 23 } 24 25 public class Lunch extends Meal { 26 public Lunch() { 27 System.out.println("Lunch constructor() "); 28 } 29 } 30 31 public class

Java 类的构造器的调用顺序

只愿长相守 提交于 2020-01-14 13:02:27
规则如下: 对于一个复杂的对象,构建器的调用遵照下面的顺序: (1) 调用父类构建器。这个步骤会不断重复下去,首先得到构建的是分级结构的根部,然后是下一个子类,等等。直到抵达最深一层的子类。 (2) 按声明顺序调用成员初始化模块。 (3) 调用子类构建器的主体。 *** 代码如下: class Meal { Meal() { System.out.println("Meal()"); } } class Bread { Bread() { System.out.println("Bread()"); } } class Cheese { Cheese() { System.out.println("Cheese()"); } } class Lettuce { Lettuce() { System.out.println("Lettuce()"); } } class Lunch extends Meal { Lunch() { System.out.println("Lunch()");} } class PortableLunch extends Lunch { PortableLunch() { System.out.println("PortableLunch()"); } } class Sandwich extends PortableLunch { Bread b =