一、概述
instanceof
运算符是做什么用的?我看过类似的东西
if (source instanceof Button) {
//...
} else {
//...
}
但是,这对我来说都没有意义。我已经完成了研究,但只提出了没有任何解释的示例。
二、详解
instanceof
keyword是用于测试对象(实例)是否为给定Type的子类型的二进制运算符。
想像:
interface Domestic {}
class Animal {}
class Dog extends Animal implements Domestic {}
class Cat extends Animal implements Domestic {}
想象一个用创建的dog
对象Object dog = new Dog()
,然后:
dog instanceof Domestic // true - Dog implements Domestic
dog instanceof Animal // true - Dog extends Animal
dog instanceof Dog // true - Dog is Dog
dog instanceof Object // true - Object is the parent type of all objects
然而,随着Object animal = new Animal();
,
animal instanceof Dog // false
因为它Animal
是的超类型,Dog
并且可能更少。
和,
dog instanceof Cat // does not even compile!
这是因为Dog
既不是的子类型也不是的超类型Cat
,并且它也不实现它。
请注意,dog
上面用于的变量是类型Object
。这是instanceof
一个运行时操作,将我们带到一个用例:在运行时根据对象类型做出不同的反应。
注意事项:expressionThatIsNull instanceof T
对于所有Types都是false T
。
如若转载,请注明出处:https://www.javaidea.cn/article/8346.html