Constructor and polymorphism (Chapter8.3), polymorphism chapter8.3

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.