标签:多态与动态绑定
声明:代码和图片是本人在学习期间复制尚学堂课件中的资料,对其做一下总结。
abstract class Animal {
private String name;
Animal(String name) {this.name = name;}
/*
public void enjoy(){
System.out.println("叫声......");
}
*/
public abstract void enjoy();
}
abstract class Cat extends Animal {
private String eyesColor;
Cat(String n,String c) {super(n); eyesColor = c;}
/*
public void enjoy() {
System.out.println("猫叫声......");
}
*/
//public abstract void enjoy();
}
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 Test {
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();
}
}
---------------------------------------------------------------
运行结果:猫叫声。。
狗叫声。。
---------------------------------------------------------------
标签:多态与动态绑定
原文地址:http://7122819.blog.51cto.com/7112819/1538637