Java物件導向之多態(向上向下轉型) 入門執行個體

來源:互聯網
上載者:User

標籤:strong   instance   animal   code   擴充   image   ota   cas   執行   

一、基礎概念

  多態:

    重點是對象的多態性。某一事物的多種體現形態。

  多態的作用:

    1.提高了代碼的擴充性,後期出現的功能,可以被之前的程式所執行。

    2.不能使用子類特有的功能。只能使用覆蓋父類的功能。

  多態的前提:

    1.必須要有繼承關係或者實現關係。

    2.通常對方法進行重寫、覆蓋。

    3.父類或者介面要引用指向子類對象。

  多態向上轉型:

    1.提高程式的擴充性,隱藏了具體子類型

    2.只能使用父類中的功能,不能使用子類特有的功能。功能被限定了。

  多態向下轉型:

    1.可以使用子類型的特有功能。

    2.必須面對具體的子類型。

    3.為了避免運行時出現ClassCastException 問題,需要用關鍵字instanceof來進行判斷。

二、代碼執行個體

 1 //父類Animal 2 abstract class Animal 3 { 4     abstract void eat(); 5     abstract void sleep(); 6 } 7  8 //Dog類繼承Animal類 9 class Dog extends Animal10 {11     /**12     將Animal類中的方法重寫13     */14     void eat()15     {16         System.out.println("dog eat 吃骨頭");17     }18     void sleep()19     {20         System.out.println("dog sleep .....");21     }22     23     /**24     自己特有的方法25     */26     void say()27     {28         System.out.println("dog say .....");29     }30 }31 32 //Cat類繼承Animal類33 class Cat extends Animal34 {35     /**36     將Animal類中的方法重寫37     */38     void eat()39     {40         System.out.println("Cat eat 吃魚");41     }42     void sleep()43     {44         System.out.println("Cat sleep .....");45     }46 }47 48 class DuoTaiDemo 49 {50     //封裝Dog類的方法51     public static void method(Dog d)52     {53         d.eat();54         d.sleep();55         d.say();56     }57     58     //封裝Cat類的方法59     public static void method(Cat c)60     {61         c.eat();62         c.sleep();63     }64     65     //封裝父類Animal的方法66     public static void method(Animal s)67     {68         s.eat();69         s.sleep();70     }71     72     public static void main(String[] args) 73     {74         Dog d1 = new Dog();75         method(d1);76     77         Cat c = new Cat();    78         method(c);79         80         Animal s = new Dog(); //多態性,向上轉型,將Dog提升為Animal。81         method(s); //只能使用覆蓋了父類Animal的eat方法和sleep方法。不能使用Dog類中自己的say方法。82         83         Animal a = new Cat(); //多態性,向上轉型。84         method(a);85     86         /**87         向下轉型,為了避免運行時出現ClassCastException 問題,88         需要用關鍵字instanceof來進行判斷。89         */90         if (s instanceof Dog)91         {92             Dog d2 = (Dog)s;93             d2.eat();94             d2.sleep();95             d2.say();96         }97     }    98 }

三、運行代碼

  

 

Java物件導向之多態(向上向下轉型) 入門執行個體

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.