00046_多态的好处与弊端

1、向上转型的好处:隐藏了子类类型,提高了代码的扩展性。

2、向上转型的弊端:只能使用父类共性的内容,而无法使用子类特有功能,功能有限制。

 1 //描述动物类,并抽取共性eat方法
 2 abstract class Animal {
 3     abstract void eat();
 4 }    
 5  
 6 // 描述狗类,继承动物类,重写eat方法,增加lookHome方法
 7 class Dog extends Animal {
 8     void eat() {
 9         System.out.println("啃骨头");
10     }
11 
12     void lookHome() {
13         System.out.println("看家");
14     }
15 }
16 
17 // 描述猫类,继承动物类,重写eat方法,增加catchMouse方法
18 class Cat extends Animal {
19     void eat() {
20         System.out.println("吃鱼");
21     }
22 
23     void catchMouse() {
24         System.out.println("抓老鼠");
25     }
26 }
27 
28 public class Test {
29     public static void main(String[] args) {
30         Animal a = new Dog(); //多态形式,创建一个狗对象
31         a.eat(); // 调用对象中的方法,会执行狗类中的eat方法
32         // a.lookHome();//使用Dog类特有的方法,需要向下转型,不能直接使用
33         
34         // 为了使用狗类的lookHome方法,需要向下转型
35 // 向下转型过程中,可能会发生类型转换的错误,即ClassCastException异常
36         // 那么,在转之前需要做健壮性判断 
37         if( !a instanceof Dog){ // 判断当前对象是否是Dog类型
38                  System.out.println("类型不匹配,不能转换"); 
39                  return; 
40         } 
41         Dog d = (Dog) a; //向下转型
42         d.lookHome();//调用狗类的lookHome方法
43     }
44 }

3、向下转型的好处:可以使用子类特有功能。

4、向下转型的弊端:需要面对具体的子类对象;在向下转型时容易发生ClassCastException类型转换异常。在转换之前必须做类型判断。

if( !a instanceof Dog){…}

5、总结

  (1)什么时候使用向上转型

  当不需要面对子类类型时,通过提高扩展性,或者使用父类的功能就能完成相应的操作,这时就可以使用向上转型。 

Animal a = new Dog();
a.eat();

  (2)什么时候使用向下转型

  当要使用子类特有功能时,就需要使用向下转型。

Dog d = (Dog) a; //向下转型
d.lookHome();//调用狗类的lookHome方法

 

posted @ 2017-12-21 19:11  gzdlh  阅读(193)  评论(0编辑  收藏  举报