类型转换和多态(也叫动态绑定)
函数在运行过程中,根据实际的对象类型,自动选取对应对象的方法。
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; // 强制类型转换,不强转换不能输出 a.furColor,其他都可以
Lady l2 = new Lady("l2",d);
l2.myPetEnjoy(); //“狗叫声……”
Lady l3 = new Lady("34",e);
l2.myPetEnjoy(); //“猫叫声……”
}
}