package jave;
/*多态的三个条件
* 1 要有继承;
* 2 要有方法的重写;
* 3 父类引用指向子类的引用对象
*/
/*动态绑定(迟绑定或者多态)--在执行期间(而非编译期间)判断引用对象的实际类型,根据其实际类型调用其相应的方法*/
abstract public class Animal {//抽象类,含有抽象方法的类必须被声明为抽象类,抽象类也不能被实例化
private String name;
Animal(String name) {
this.name = name;
}
public abstract void enjoy();//抽象方法(即C++中的纯虚函数),反正下面都要重写此方法,写不写都无所谓
// public void enjoy() {
// System.out.println("叫声……");
// }
public static void main(String[] args) {
Bird b = new Bird("catname", "blue");
Monkey m = new Monkey("dogname", "black");
Lady l1 = new Lady("l1", b);
Lady l2 = new Lady("l2", m);
l1.myPetEnjoy();
l2.myPetEnjoy();
}
}
class Bird extends Animal {
private String eyesColor;
Bird(String n, String c) {
super(n);
eyesColor = c;
}
public void enjoy() {
System.out.println("鸟叫声……");
}
}
class Monkey extends Animal {
private String furColor;
Monkey(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();
}
}