1 package cn.zmh.A; 2 3 //动物类 4 public class Animal { 5 void eat(){ 6 7 } 8 } 9 10 //猫类 11 class Cat extends Animal { 12 void eat(){ 13 System.out.println("猫吃鱼"); 14 } 15 } 16 17 //狗类 18 class Dog extends Animal { 19 void eat(){ 20 System.out.println("狗吃骨头"); 21 } 22 } 23 24 //人类 喂猫喂狗 25 class Persosn extends Animal { 26 void feedAnimal(Animal anim){ 27 28 //打印运行的地址 29 anim.eat(); 30 } 31 } 32 33 //测试类 34 class TestAnimal { 35 36 37 public static void main(String[] args){ 38 //多态写法 39 Animal d = new Dog(); 40 Animal c = new Cat(); 41 42 Persosn p = new Persosn(); 43 44 //子类的值d赋值给父类Animal 45 Animal aimn = (Animal) d; 46 p.feedAnimal(aimn); 47 48 //子类的值c赋值给父类Animal 49 Animal aimn1 = (Animal) c; 50 p.feedAnimal(aimn1); 51 52 } 53 }