Java多态之引用类型转换

来源:互联网 发布:台账软件 编辑:程序博客网 时间:2024/06/05 18:07

其中AnimalDogCat类在Java多态这篇文章中

public static void main(String[] args) {        /*         * 基本数据类型中,存在类型转换         * int i=1;         * short s=(short)i;//强制转换为short类型         */        //在多态中也需要进行类型转换        Animal a=new Dog();        //Dog d=a;//编译报错:类型不匹配:不能从 Animal 转换为 Dog        //强制类型转换        Dog d=(Dog)a;//编译正确        a.eat();//输出: dog eat bone        Animal c=new Cat();        //Cat c=(Cat)a;        /*         * 编译正确,但是运行错误:Dog cannot be cast to Cat         * 因为即使加了强制转换,Dog也不能转换为Cat         * 所以在转换时,实际是什么类型就转换为什么类型         */        /*         * 关键字 instanceof          * 作用:判断对象是否是一个类的 实例         * 用法:boolean b=对象名 instanceof 类名         * 若对象是类的实例,返回true         * 若对象时类的父类的实例,也返回true         */        if(a instanceof Dog){//true            System.out.println("a是Dog类型");        }        if(c instanceof Dog){//false            System.out.println("c是Dog类型");        }        else{            System.out.println("c不是Dog类型");        }        /*         * 当需要知道对象是否是真是实例的类型时         * 用getClass方法         * 用法:对象名.getClass() == 另一对象名.getClass()         */        if(d.getClass()==a.getClass()){//都为Dog类型,输出相同            System.out.println("a和d类型相同");        }        else{            System.out.println("a和d类型不相同");        }        if(d.getClass()==c.getClass()){//d为Dog类型,c为Cat类型,输出不同            System.out.println("c和d类型相同");        }        else{            System.out.println("c和d类型不相同");        }    }
0 0