什么是Java中使用的'instanceof'运算符? [英] What is the 'instanceof' operator used for in Java?

查看:100
本文介绍了什么是Java中使用的'instanceof'运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 keyword是一个二元运算符,用于测试对象(实例)是否是给定Type的子类型。

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

然而,使用对象动物=新动物();

animal instanceof Dog // false

因为 Animal 的超类型,可能更少精炼。

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.

注意用于<$的变量c $ c> 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.

注意事项:对于所有类型<$ c,expressionThatIsNull instanceof T 为false $ c> T 。

Things to note: expressionThatIsNull instanceof T is false for all Types T.

快乐编码。

这篇关于什么是Java中使用的'instanceof'运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆