问题描述
instanceof
运算符的用途是什么?我见过类似的东西
What is the instanceof
operator used for? I've seen stuff like
if (source instanceof Button) {
//...
} else {
//...
}
但对我来说没有任何意义.我已经做了我的研究,但只是举了例子,没有任何解释.
But none of it made sense to me. I've done my research, but came up only with examples without any explanations.
推荐答案
instanceof
关键字是一个二元运算符,用于测试一个对象(instance) 是给定类型的子类型.
instanceof
keyword is a binary operator used to test if an object (instance) is a subtype of a given Type.
想象一下:
interface Domestic {}
class Animal {}
class Dog extends Animal implements Domestic {}
class Cat extends Animal implements Domestic {}
想象一个 dog
object,用 Object dog = new Dog()
创建,然后:
Imagine a dog
object, created with Object dog = new Dog()
, then:
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
然而,使用Objectanimal = new Animal();
,
animal instanceof Dog // false
因为Animal
是Dog
的超类型并且可能不那么精致".
because Animal
is a supertype of Dog
and possibly less "refined".
还有,
dog instanceof Cat // does not even compile!
这是因为Dog
既不是Cat
的子类型也不是超类型,也没有实现.
This is because Dog
is neither a subtype nor a supertype of Cat
, and it also does not implement it.
请注意,上面用于 dog
的变量是 Object
类型.这是为了表明 instanceof
是一个 运行时 操作,并将我们带到一个/用例:在运行时根据对象类型做出不同的反应.
Note that the variable used for dog
above is of type Object
. This is to show instanceof
is a runtime operation and brings us to a/the use case: to react differently based upon an objects type at runtime.
注意事项:expressionThatIsNull instanceof T
对于所有类型 T
都是假的.
Things to note: expressionThatIsNull instanceof T
is false for all Types T
.
这篇关于Java 中使用的“instanceof"运算符是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!