多态的优缺点

优点:

  提高了代码的维护性(继承保证)

  提高了代码的扩展性(多态保证)

缺点:

  不能使用子类的特有功能

 1 class duotaidemo{
 2     public static void main(String[] args) {
 3         Fu f = new Zi();    //向上转型
 4         f.show();
 5         //f.method();
 6         Zi z = (Zi)f;   //向下转型
 7         z.method();
 8     }
 9     public static class Fu{
10         public void show() {
11             System.out.println("show fu");
12         }
13     }
14     
15     public static class Zi extends Fu{
16         public void show() {
17             System.out.println("show zi");
18         }
19         
20         public void method() {
21             System.out.println("method zi");
22         }
23     }
24 }

运行结果:

show zi
method zi

如果想使用子类的特有功能 就把父类的引用强转为子类的引用。

 

向上转型:
            Fu f = new Zi();
        向下转型:
            Zi z = (Zi)f; //要求该f必须是能够转换为Zi的。

posted @ 2019-07-21 19:58  路还很长  阅读(1612)  评论(0编辑  收藏  举报