假设我们分别有一个名为Child
和Parent
的基类和父类。
Parent b = new Child();
System.out.println(b instanceof Child);// prints true.
System.out.println(b instanceof Parent);//prints true.
那么为什么两个陈述都是真的呢?
答案 0 :(得分:2)
答案 1 :(得分:1)
instanceof
检查对象动态 类型的关系“IS”
Animal a = new Dog() //Dynamic type of a is Dog
d instanceof Animal // TRUE
因为狗是动物。
所以instanceof
查看Animal的分支并发现Dog是Animal的孩子,因此返回true。
然而:
a instance of Dog // FALSE
因为动物不一定是狗
结论:X instanceof Y
,为此,Y必须是X的父级或同一分支中相同类型的X
答案 2 :(得分:1)
instanceof
运算符将对象与指定类型进行比较。您可以使用它来测试对象是否是类的实例,子类的实例或实现特定接口的类的实例。
了解更多Oracle Java Tutorial - The Type Comparison Operator instanceof
注意:使用instanceof
运算符时,请注意null
不是任何实例。
例如:
String name = null;
System.out.println((name instanceof String)); // prints false
Parent p = new Child();
System.out.println(p.getClass().isAssignableFrom(Parent.class)); // return false
System.out.println(p.getClass().isAssignableFrom(Child.class)); // return true