instanceofkeyword是用于测试对象(实例)是否为给定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 Domesticdog instanceof Animal // true - Dog extends Animaldog instanceof Dog // true - Dog is Dogdog 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。



