Java 如何检查可能不是指定类实例的对象的类型?

Java 如何检查可能不是指定类实例的对象的类型?,java,Java,此代码试图检查对象的类型 class Animal{} class Cat extends Animal{} class Dog extends Animal{} class InheritanceXP{ public static void main(String args[]){ Dog adog = new Dog(); System.out.println(adog instanceof Animal); System.out.pr

此代码试图检查对象的类型

class Animal{}
class Cat extends Animal{}
class Dog extends Animal{}
class InheritanceXP{
    public static void main(String args[]){
        Dog adog = new Dog();
        System.out.println(adog instanceof Animal);
        System.out.println(adog instanceof Dog);
        try{
            System.out.println(adog instanceof Cat);
        } catch (Exception e){
            System.out.println(e);
        }
    }
}
其中两个,adog instanceof Animal和adog instanceof Dog运行良好,但最后一个,adog instanceof Cat在编译过程中不断抛出不兼容的类型错误,即使我将其放在try块中

怎么做?

try/catch是一个运行时构造。这是当代码块在运行时可能引发异常时所做的事情

狗adog=新狗;是一个编译时构造。它显式地告诉编译器类型是Dog,它与Cat没有关系,因此它不必等到运行应用程序时才知道它不会工作

如果希望代码块正常工作,请将声明的类型更改为Animal。 动物adog=新狗;如果声明的类型是Animal,那么在运行时它可能是Cat,并且您的代码将被编译。

adog不是Cat的实例,尽管它们共享同一个超类。因此,它将继续抛出不兼容的类型。请看这里: