package DuoTai;
/**
* 多态的一些基本知识
* 在子类和父类里面有同名函数的时候,假如生成一个子类的对象,并在子类的对象里面
调用这个函数,那么到底会是调用的是谁的函数呢?
* 1.要有继承
* 2.要有重写
* 3.父类引用指向子类对象
* 当你调用调用父类里被重写的方法时,实际当中new的是哪个子类对象就调用哪个子类对象的方法
* @author Administrator
*
*/
class Animal{
private String name;
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); furColor = c;}
public void enjoy() {
System.out.println("狗叫声......");
}
}
class Bird extends Animal {
Bird() {
super("bird");
}
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 DuoTaiTest {
public static void main(String args[]){
Cat c = new Cat("catname","blue");
Dog d = new Dog("dogname","black");
Bird b = new Bird();
Lady l1 = new Lady("l1",c);
Lady l2 = new Lady("l2",d);
Lady l3 = new Lady("l3",b);
l1.myPetEnjoy();
l2.myPetEnjoy();
l3.myPetEnjoy();
}
}