动态绑定,也叫多态。
TestPolymoph.java
class="java" name="code">//java动态绑定和多态 //动态绑定,也叫多态。 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;//宠物Animal类 Lady(String name,Animal pet) { this.name = name; this.pet = pet; } //我的宠物高兴了 public void myPetEnjoy(){ pet.enjoy(); } } /* 动态绑定总结: 1.要有继承 2.要有重写 3.父类引用指向子类对象 */ public class TestPolymoph { 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); //根据实际的对象来确定调用的方法,不是通过引用类型来确定的,不然就就一定调用Animal中的enjoy()方法, l1.myPetEnjoy(); l2.myPetEnjoy(); l3.myPetEnjoy(); } }
?