1 public class TestAnimal { 2 public static void main(String[] args) { 3 TestAnimal t = new TestAnimal(); 4 t.func(new Animal()); 5 t.func(new Dog()); 6 7 t.func(new Cat()); 8 9 } 10 public void func(Animal a){//Animal a = new Dog(); 11 a.eat(); 12 a.jump(); 13 14 if(a instanceof Dog){ 15 Dog d = (Dog)a; 16 d.Wang(); 17 } 18 if(a instanceof Cat){ 19 Cat c = (Cat)a; 20 c.catchMouse(); 21 } 22 } 23 // public void func(Dog a){ 24 // a.eat(); 25 // a.jump(); 26 // } 27 } 28 class Animal{ 29 String name; 30 int age; 31 32 public void eat(){ 33 System.out.println("进食"); 34 } 35 public void jump(){ 36 System.out.println("跳"); 37 } 38 } 39 class Dog extends Animal{ 40 public void eat(){ 41 System.out.println("狗吃食"); 42 } 43 public void jump(){ 44 System.out.println("狗急跳墙"); 45 } 46 47 public void Wang(){ 48 System.out.println("汪汪叫"); 49 } 50 } 51 52 class Cat extends Animal{ 53 public void eat(){ 54 System.out.println("猫吃鱼"); 55 } 56 public void jump(){ 57 System.out.println("猫跳"); 58 } 59 public void catchMouse(){ 60 System.out.println("猫抓老鼠"); 61 } 62 }