1 abstract class Animal {
2 String name;
3 String color;
4
5 public Animal(String name, String color) {
6 this.name = name;
7 this.color = color;
8 }
9
10 public abstract void run();
11 }
12
13 class Dog extends Animal {
14
15 public Dog(String name, String color) {
16 super(name, color);
17 }
18
19 public void run() {
20 System.out.println(color + name + "四条腿跑");
21 }
22
23 public void find() {
24 System.out.println(color + name + "找骨头");
25 }
26 }
27
28 class fish extends Animal {
29
30 public fish(String name, String color) {
31 super(name, color);
32 }
33
34 public void run() {
35 System.out.println(color + name + "游的快");
36 }
37
38 public void eat() {
39 System.out.println(color + name + "吃面包屑");
40 }
41 }
42
43 public class Demo {
44 public static void main(String[] args) {
45 // Animal a = new fish("小鱼", "黄色");
46 // 强制类型转换就能调用到子类的方法
47 // fish f = (fish) a;
48 // f.eat();
49
50 fish f = new fish("小鱼", "黄色");
51 printThe(f);
52 Dog d = new Dog("小狗", "花的");
53 printThe(d);
54 }
55
56 // 定义一个函数接收任意类型的动物对象,在函数内部调用动物特有的方法
57 public static void printThe(Animal a) {
58 if (a instanceof fish) {
59 fish f = (fish) a;
60 f.eat();
61 } else if (a instanceof Dog) {
62 Dog d = (Dog) a;
63 d.find();
64 }
65 }
66 }