1 public static void show(Animal1 a){ 2 a.eat(); 3 if (a instanceof Cat){//判断a是哪个类new出来的对象 4 Cat cat =(Cat)a; //因为a是Animal1的对象,它可以指向猫或者狗,所以到了这一步得指向相应的类对象 5 cat.work(); 6 ((Cat) a).work(); 7 } 8 if (a instanceof Dog1){ 9 Dog1 dog = (Dog1)a; 10 dog.work(); 11 } 12 } 13 abstract static class Animal1{//抽象类的方法必须由子类来实现,除非抽象类的方法也是抽象方法 14 abstract void eat(); 15 } 16 public static class Cat extends Animal1{ 17 public void eat(){ 18 System.out.println("猫吃鱼"); 19 } 20 public void work(){ 21 System.out.println("猫抓老鼠"); 22 } 23 } 24 public static class Dog1 extends Animal1{ 25 public void eat(){ 26 System.out.println("狗吃骨头"); 27 } 28 public void work(){ 29 System.out.println("狗看家"); 30 } 31 } 32 public static void main(String[] args) { 33 show(new Cat()); // Animal1 a = new Cat(); 创建的是Animal1的对象,此时它可以指向猫,也可以指向狗 34 show(new Dog1()); 35 Animal1 am = new Cat(); 36 show(am); 37 am.eat(); 38 Cat c = new Cat(); 39 c.work(); 40 Dog1 dg = new Dog1(); 41 }