類型轉換和多態
類型轉換和多態(也叫動態綁定)
函數在運行過程中,根據實際的對象類型,自動選取對應對象的方法。
class Animal {
private String name;
Animal(String name) {this.name = name;}
public void enjoy(){
System.out.println("動物叫聲......");
}
}
class Dog extends Animal {
private String furColor;
Dog(String n,String c) {super(n); furColor = c;}
public void enjoy() {
System.out.println("狗叫聲......");
}
}
class Cat extends Animal {
private String furColor;
Cat(String n,String c) {super(n); furColor = c;}
public void enjoy() {
System.out.println("貓叫聲......");
}
}
class Lady {
private String name;
private Animal pet; //定義一個父類的引用對象,方便函數的擴展
Lady(String name,Animal pet) {
this.name = name; this.pet = pet;
}
public void myPetEnjoy(){pet.enjoy();}
}
public class Test {
public static void main(String args[]){
Animal a = new Cat("Catname","blue");
Dog d = new Dog("dogname","black");
Cat e = (Cat) a; // 強制類型轉換,不強轉換不能輸出
Lady l2 = new Lady("l2",d);
l2.myPetEnjoy(); //“狗叫聲……”
Lady l3 = new Lady("34",e);
l2.myPetEnjoy(); //“貓叫聲……”
}
}
類型轉換和多態