java笔记--day09--多态(二)

来源:互联网 发布:淘宝香火符咒西极飞飞 编辑:程序博客网 时间:2024/06/12 12:57
  • 引言
    从上一个笔记中,可以看出,多态的向上转型(Fu f = new Zi();)是不能访问子类中特有功能的。那么其解决办法是什么呢?

    • 向下转型(downcasting)
  • 以下代码为未转型的代码:

class Fu{    int num1;    public Fu(){        num1 = 10;    }    public void show1(){        System.out.println("num1 is " + num1);    }    public static void show3(){        System.out.println("static function in Fu class");    }}class Zi extends Fu{    int num1 = 11;    int num2 = 20;    public Zi(){}    public void show1(){        System.out.println("num1 is " + num1);    }    public void show2(){        System.out.println("num2 is " + num2);    }    public static void show3(){        System.out.println("static function in Zi class");    }}class PolymorphicDemo2{    public static void main(String[] args) {        Fu f = new Zi();        System.out.println("num1 is " + f.num1); //member variable        //System.out.println("num2 is " + f.num2); //This line must be commented out,or there is a fail during compilation.                                                 //(error:can not find the symbol)        f.show1();        //f.show2();//This line must be commented out,or there is a fail during compilation.                    //(error:can not find the symbol)           f.show3();//static member method    }}/*running result:num1 is 10num1 is 11static function in Fu class*/
  • 然后是使用了向下转型之后,能访问子类特有功能的Demo:
class Fu{    int num1;    public Fu(){        num1 = 10;    }    public void show1(){        System.out.println("Fu num1 is " + num1);    }    public static void show3(){        System.out.println("static function in Fu class");    }}class Zi extends Fu{    int num1 = 11;    int num2 = 20;    public Zi(){}    public void show1(){        System.out.println("Zi num1 is " + num1);    }    public void show2(){        System.out.println("Zi num2 is " + num2);    }    public static void show3(){        System.out.println("static function in Zi class");    }}class PolymorphicDemo2{    public static void main(String[] args) {        Fu f = new Zi();        System.out.println("num1 is " + f.num1); //member variable        //System.out.println("num2 is " + f.num2); //This line must be commented out,or there is a fail during compilation.(error:can not find the symbol)        f.show1();        //f.show2();//This line must be commented out,or there is a fail during compilation.(error:can not find the symbol)         f.show3();//static member method        System.out.println();        Zi z = (Zi)f;        z.show2();    }}/*running result:num1 is 10Zi num1 is 11static function in Fu classZi num2 is 20*/
  • 总结
    从running result的最后一句话(Zi num2 is 20)中可以看出:
    使用了向下转型(Zi z = (Zi)f;),就可以摆脱多态的弊端,从而可以访问子类所特有的功能
0 0
原创粉丝点击