Java-用instanceof关键字进行类型判断

判断引用的类是猫还是狗?

如何才能知道一个父类引用的对象,本来是什么子类?
格式:
对象 instanceof 类名称
这将会得到一个boolean值结果,也就是判断前面的对象能不能当做后面类型的实例。

public class Demo02Instanceof {

public static void main(String[] args) {
    Animal animal = new Cat();//本来是一只猫 或 者 狗
    animal.eat();//猫吃鱼

    //如果希望调用子类特有方法,需要向下转型
    //判断父类引用animal本来是不是Dog
    if (animal instanceof Dog) {
        Dog dog = (Dog) animal;
        dog.watchHouse();
    }

    if (animal instanceof Cat) {
        Cat cat = (Cat) animal;
        cat.catchMouse();
    }
    giveMeAPet(new Dog());//调用女朋友要宠物的方法
}

//如果女朋友找你要一只宠物,就可以判断是什么,知道是什么,能干什么?

public static void GiveMeAPet(Animal animal) {
//
if(animal instanceof Dog) {
Dog dog = (Dog) animal;
dog.watchHouse();
}
if(animal instanceod Cat){
Cat cat = (Cat) animal;
cat.catchMouse();
}
}

注意:
向下转型一定要使用instanceof判断,否则会发生类转换异常。

上一篇:Day013 instanceof和类型转换


下一篇:多态