Java三大特征--多态

来源:互联网 发布:福建广电网络爱家app 编辑:程序博客网 时间:2024/05/16 07:44

1、程序运行的最终结果只在执行期间才被确定,编译时无法确定
2、编译时所用参数类型一般为父类,运行时参数类型为确定的子类
3、三个必要条件:要有继承,子类要有方法的重写,父类引用指向子类对象(只可向上转型,不可向下转型)

测试例子如下:

package cn.ldedu;/** * 测试多态 * @author Lenovo * */class Animal{    public void sing(){        System.out.println("aaa");    }}class Cat extends Animal{    public void sing(){        System.out.println("喵喵喵");    }    public void catchMouse(){        System.out.println("抓老鼠");    }}class Dog extends Animal{    public void sing(){        System.out.println("汪汪汪");    }}/** * 测试类 * @author Lenovo * */public class testduotai {    public void testsing(Animal a){        a.sing();        // 测试instanceof方法        if(a instanceof Cat)            ((Cat)a).catchMouse();//调用方法前一定要强制转型    }    public static void main(String[] args) {        testduotai tt=new testduotai();        //Animal 向下转型为Cat        Animal a=new Cat();         Dog b=new Dog();//避免了转型,但是不推荐使用        tt.testsing(a);        tt.testsing(b);        //此时若"a"想调用catchMouse方法,需要强制转型,或者也可以在测试方法中利用instanceof方法调用catchMouse方法        Cat cc=(Cat)a;        cc.catchMouse();    }}

运行截图:这里写图片描述

关于抽象类、接口、回调会在其他文章详细描述