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 运算符通常用于在运行时进行类型检查,以确保在进行类型转换之前不会出现类型错误。

相关推荐
殷紫川1 小时前
90% Java 开发都踩过坑的 @Resource 与 @Autowired
java
kybs19911 小时前
springboot租车系统--附源码68701
java·hadoop·spring boot·python·django·asp.net·php
过期动态2 小时前
MySQL中的约束
android·java·数据库·spring boot·mysql
wxin_VXbishe2 小时前
springboot新能源车充电站管理系统小程序-计算机毕业设计源码29213
java·c++·spring boot·python·spring·django·php
程序员陆通2 小时前
月烧 400 刀到不到 20 刀:我是怎么把 OpenClaw 的 Token 账单砍掉 95% 的
java·前端·数据库
代码漫谈2 小时前
一文学习 SpringBoot 的 application.yml 配置,基于 Spring Boot 3.2.x
java·spring boot·spring·配置文件
SamDeepThinking2 小时前
程序员如何接受工作内容毫无意义?
java·后端·程序员
三翼鸟数字化技术团队3 小时前
基于Redis ZSet实现分布式优先级队列的技术实践
java·redis
无所事事O_o3 小时前
加密过程及原理浅析
java·加密
2301_771717213 小时前
最近在刷牛客:使用Spring AOP实现性能监控时
java·后端·spring