1 package face_09;
2
3 import com.sun.jdi.Method;
4
5 /*
6 * 对象的多态性。
7 * class 动物
8 * {}
9 *
10 * class 猫 extends 动物
11 * {}
12 *
13 * class 狗 extends 动物
14 * {}
15 *
16 * 猫 x = new 猫();
17 *
18 * 动物 x = new 猫();//一个对象,两种形态。
19 *
20 * 猫这类事物既具备猫的形态,又具备着动物的形态。
21 * 这就是对象的多态性。
22 *
23 * 简单说:就是一个对象对应着不同类型。
24 *
25 * 多态在代码中的体现:
26 * 父类或者接口的引用指向其子类的对象。
27 * 多态的好处:
28 * 提高了代码的扩展性,前期定义的代码可以使用后期的内容。
29 *
30 * 多态的弊端:
31 * 前期定义的内容不能使用(调用)后期子类的特有内容。
32 *
33 * 多态的前提:
34 * 1,必须有关系,继承,实现。
35 * 2,要有覆盖。
36 */
37 abstract class Animal {
38 abstract void eat();
39 }
40
41 class Dog extends Animal {
42 void eat() {
43 System.out.println("啃骨头");
44 }
45 void lookHome() {
46 System.out.println("看家");
47 }
48 }
49 class Cat extends Animal {
50 void eat() {
51 System.out.println("吃鱼");
52 }
53 void catchMouse() {
54 System.out.println("抓老鼠看家");
55 }
56 }
57 class Pig extends Animal {
58 void eat() {
59 System.out.println("饲料");
60 }
61 void gongDi() {
62 System.out.println("拱地");
63 }
64 }
65 public class DuoTaiDemo {
66 public static void main(String[] args) {
67 //Cat c = new Cat();
68 //c.eat();
69 //Dog d = new Dog();
70 //method(c);
71 //method(d);
72 //method(new Pig());
73 Animal a = new Cat();//自动类型提升,猫对象提升了动物类型。但是特有功能无法访问
74 //作用就是限制对特有功能的访问。
75 //专业讲:向上转型。将子类型隐藏。就不用使用子类型的方法。
76 //如果还想用具体动物猫的特有功能。
77 //你可以将该对象进行向下转型。
78 Cat c = (Cat)a;//*向下转型的目的是为了使用子类中的特有方法。
79 c.catchMouse();
80 c.eat();
81 //*注意:对于转型,自始至终都是子类对象在做着类型的变化
82 //Animal a1 = new Animal();
83 Animal a1 = new Dog();
84 Cat c1 = (Cat)a1;//ClassCastException类型转换异常
85 //a.eat();
86 }
87 public static void method(Animal a) {//类型判断
88 a.eat();
89 if(a instanceof Cat) {//instanceof:用于判断对象的具体类型。Cat可以是类可以是接口,只能用于引用数据类型判断
90 Cat c = (Cat)a;//通常在向下转型前用于健壮性的判断。
91 c.catchMouse();
92 }else if (a instanceof Dog) {
93 Dog d = (Dog)a;
94 d.lookHome();
95 }
96 }
97 /*
98 public static void method(Cat c) {
99 c.eat();
100 }
101 public static void method(Dog d) {
102 d.eat();
103 }
104 */
105
106 }