/**多态是指执行期间(而非编译期间)判断所印象对象的实际类型,根据其实际的类型调用相应的方法。 多态存在的三个必要条件: 一、要有继承 二、要有重写 三、父类引用指向子类对象 多态的有点: 使得程序的扩张性达到极致
*/ abstract class Animal { private String name; Animal(String name) {this.name = name;} public void enjoy(){ System.out.println("叫声......"); } // public abstract void enjoy(); } 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(); } }
JAVA基础学习之多态
最新推荐文章于 2024-05-28 22:18:08 发布