構造器和多態(Chapter8.3),多態chapter8.3

來源:互聯網
上載者:User

構造器和多態(Chapter8.3),多態chapter8.3

構造器不具有多態性(它們是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      */// :~
View Code

銷毀的順序應該和初始化的順序相反

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.