Constructor and polymorphism (Chapter8.3), polymorphism chapter8.3
Constructors do not have polymorphism (they are static methods, but the static declaration is implicit), but it is still necessary to understand how constructors operate in a complex hierarchy through polymorphism, this understanding will help you avoid some unpleasant troubles.
Create an object in main to call the constructor in the following order:
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 */// :~View Code
The destruction sequence should be the opposite of the initialization sequence.