//动态绑定是指在执行期间(而非编译期间)判断所引用对象的实际类型,根据其实际类型调用其相应的方法。
public class Test {
public static void main(String args[]) {
Cat c = new Cat("catname", "blue");
Dog d = new Dog("dogname", "black");
Lady lady1=new Lady("l1", c);
Lady lady2=new Lady("l2", d);
lady1.myPetEnjoy();
lady2.myPetEnjoy();
}
}
class Animal {
private String name;
public Animal(String name) {
this.name = name;
}
public void enjoy() {
System.out.println("动物叫声。。。");
}
}
class Cat extends Animal {
private String eyesColor;
Cat(String n, String c) {
super(n);
eyesColor = c;
}
public void enjoy() {
System.out.println("猫叫声。。。");
}
}
class Dog extends Animal {
private String furColor;
Dog(String n, String c) {
super(n);
this.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();
}
}