构造器不具有多态性(它们是static方法,只不过该static声明是隐式的),但还是非常有必要理解构造器怎样通过多态在复杂的层次结构中运作,这一理解将有助于大家避免一些令人不快的困扰。
在main中创建对象调用构造器的顺序:
- 将分配给对象的存储空间初始化成二进制的零。
- 调用基类构造器。
- 按声明顺序调用成员的初始化方法。
- 调用导出类构造器的主体。
1 //: polymorphism/Sandwich.java 2 // Order of constructor calls. 3 package polymorphism; 4 5 import static net.mindview.util.Print.*; 6 7 class Meal { 8 Meal() { 9 print("Meal()"); 10 } 11 } 12 13 class Bread { 14 Bread() { 15 print("Bread()"); 16 } 17 } 18 19 class Cheese { 20 Cheese() { 21 print("Cheese()"); 22 } 23 } 24 25 class Lettuce { 26 Lettuce() { 27 print("Lettuce()"); 28 } 29 } 30 31 //class Pickle{ 32 // Pickle(){ 33 // print("Pickle()"); 34 // } 35 //} 36 37 class Lunch extends Meal { 38 Lunch() { 39 print("Lunch()"); 40 } 41 } 42 43 class PortableLunch extends Lunch { 44 PortableLunch() { 45 print("PortableLunch()"); 46 } 47 } 48 49 public class Sandwich extends PortableLunch { 50 private Bread b = new Bread(); 51 private Cheese c = new Cheese(); 52 private Lettuce l = new Lettuce(); 53 // private Pickle p = new Pickle(); 54 55 public Sandwich() { 56 print("Sandwich()"); 57 } 58 59 public static void main(String[] args) { 60 new Sandwich(); 61 } 62 } /* 63 * Output: Meal() Lunch() PortableLunch() Bread() Cheese() Lettuce() 64 * Sandwich() 65 */// :~
销毁的顺序应该和初始化的顺序相反