JAVA多态——类型判断

来源:互联网 发布:cats vs dogs数据下载 编辑:程序博客网 时间:2024/06/05 20:52
abstract class Animal           //定义了一个动物类,其方法有吃东西{    abstract void eat();}class Dog extends Animal        //定义了一个继承于动物类的狗类,其方法有 吃东西 和 看家{    void eat()    {        System.out.println("啃骨头");    }    void lookHome()    {        System.out.println("看家");    }}class Cat extends Animal        //定义了一个继承于动物类的猫类,其方法有 吃东西 和 抓老鼠{    void eat()    {        System.out.println("吃鱼");    }    void catchMouse()    {        System.out.println("抓老鼠");    }}

以上为类定义。
要使用子类的特有方法,需要对定义的对象进行向下转型

class Demo{//在method方法中执行对象通用的eat()方法,然后判断对象具体类型,然后根据相应类型对对象进行向下转型,然后执行对象的特殊方法。    static void method(Animal a)    {        a.eat();        // instanceof :用于判断对象的具体类型,只能用于引用数据判断,返回BOOL值        if(a instanceof Cat)//如果a的类型为Cat,为真,否则为假        {            Cat c = (Cat)a;            c.catchMouse();        }        else if(a instanceof Dog)        {            Dog c = (Dog)a;            c.lookHome();        }    }    public static void main(String[] args)                  {        Dog d = new Dog();    }}
原创粉丝点击