public class TestCasting2{ public static void main(String args[]){ TestCasting2 test2= new TestCasting2(); Animal a = new Animal("animalName"); Dog d = new Dog("dogName","dogColor"); Cat c = new Cat("catName","catColor"); test2.f(a); test2.f(d); test2.f(c); } public void f(Animal a){ //父類引用型參數(shù),達到了面向?qū)ο罂嗫嘧非蟮目蓮?fù)用性,多種類型的對象,共同使用一個方法 System.out.PRintln(a.name); if(a instanceof Dog){ Dog d2 = (Dog)a; //強制轉(zhuǎn)換,然后就可以使用子類當中的屬性了 System.out.println(d2.folorColor); }else if(a instanceof Cat){ Cat c2 = (Cat)a; System.out.println(c2.eyesColor); } //這里有過還有一個鳥對象,只需要加一個if判斷語句就ok了,不需要重寫一個方法public void f2(Bird bird){} }}class Animal{ public String name; public Animal(String name){ this.name = name; }}class Dog extends Animal{ public String folorColor; public Dog(String name,String folorColor){ super(name); this.folorColor = folorColor; }}class Cat extends Animal{ public String eyesColor; public Cat(String name,String eyesColor){ super(name); this.eyesColor = eyesColor; }}程序運行結(jié)果:

總結(jié):
這邊文章的基本記錄就是:我們創(chuàng)建一個方法,方法的參數(shù)是父類的引用。而我們實際當中傳的是子類的對象,這樣我們就可以多個對象同時使用這一個方法了。然后我們在方法中通過強制類型轉(zhuǎn)換,調(diào)用各個對象的各個屬性。
通過這種對象的向上轉(zhuǎn)型方法可以使我們的代碼可復(fù)用性提高一些,但并不是可復(fù)用性達到了最好,詳情見下一遍文章。
通過對象轉(zhuǎn)型,達到了面向?qū)ο蟮目蓮?fù)用性。就好比:我要蓋好一座大樓,然后要在大樓邊上加一個廚房,我們只需直接蓋廚房就好了。而不是將樓房的主題建筑拆掉,然后重新蓋一次樓房。
新聞熱點
疑難解答