instanceof是什么~

instanceof 是 Java 中的一个运算符,用于检查一个对象是否是某个类的实例,或者是否是该类的子类的实例。它的语法形式为:

object instanceof Class

其中,object 是要检查的对象,Class 是要检查的类名或接口名。

如果 objectClass 的实例,或者是 Class 的子类的实例,则 instanceof 运算符返回 true;否则返回 false

class Animal {}

class Dog extends Animal {}

public class Main {

public static void main(String\[\] args) {

Animal animal = new Dog();

System.out.println(animal instanceof Animal); // true

System.out.println(animal instanceof Dog); // true

System.out.println(animal instanceof Object); // true

}

}

在示例中,animalAnimal 类型的引用,指向一个 Dog 对象。因此,animal instanceof Animal 返回 true,表示 animalAnimal 类的实例;animal instanceof Dog 也返回 true,表示 animalDog 类的实例;animal instanceof Object 返回 true,因为所有类都是 Object 类的子类。

instanceof 运算符通常用于在运行时进行类型检查,以确保在进行类型转换之前不会出现类型错误。

相关推荐
St_rive1 天前
Page Object设计模式
java·开发语言·设计模式
风流 少年1 天前
Spring AI 2.0:SSE
java·人工智能·spring
凤山老林1 天前
精细化流量治理:Spring Boot 动态特性开关与灰度发布体系
java·spring boot·后端
Aphelios3801 天前
一次锁内网络IO引发的Tomcat线程池“饿死”事故
java·开发语言·spring boot·elasticsearch·tomcat·网络io阻塞·线程池耗尽
不可求~1 天前
C++ std::string_view 不是字符串:从悬空引用到安全用法
java·开发语言·c++
Lam Tang1 天前
APS 系列文章10
java·代理模式
考虑考虑1 天前
Excel导入时产生特殊字符处理
java·后端·java ee
Scabbards_1 天前
面试Leetcode - Heap 堆
java·leetcode·面试
程序员清风1 天前
专业再升级!程序员专属显示器明基RD280UG上手实测!
java·后端·面试
我命由我123451 天前
RxJava - 冷数据流与热数据流
android·java·java-ee·android studio·rxjava·android-studio·android runtime