多态的存在有三个必要条件:
1.要有继承
2.要有重写
3.父类引用指向子类对象
1 class Animal { 2 private String name; 3 Animal(String name) {this.name = name;} 4 5 public void enjoy(){ 6 System.out.println("叫声......"); 7 } 8 } 9 10 class Cat extends Animal { 11 private String eyesColor; 12 Cat(String n,String c) {super(n); eyesColor = c;} 13 14 public void enjoy() { 15 System.out.println("猫叫声......"); 16 } 17 } 18 19 class Dog extends Animal { 20 private String furColor; 21 Dog(String n,String c) {super(n); furColor = c;} 22 23 public void enjoy() { 24 System.out.println("狗叫声......"); 25 } 26 } 27 28 class Bird extends Animal { 29 Bird() { 30 super("bird"); 31 } 32 public void enjoy() { 33 System.out.println("鸟叫声......"); 34 } 35 } 36 37 class Lady { 38 private String name; 39 private Animal pet; 40 Lady(String name,Animal pet) { 41 this.name = name; this.pet = pet; 42 } 43 public void myPetEnjoy(){pet.enjoy();} 44 } 45 46 public class Test { 47 public static void main(String args[]){ 48 Cat c = new Cat("catname","blue"); 49 Dog d = new Dog("dogname","black"); 50 Bird b = new Bird(); 51 Lady l1 = new Lady("l1",c); 52 Lady l2 = new Lady("l2",d); 53 Lady l3 = new Lady("l3",b); 54 l1.myPetEnjoy(); 55 l2.myPetEnjoy(); 56 l3.myPetEnjoy(); 57 } 58 }
时间: 2024-10-10 05:16:47