当前位置: 首页 > news >正文

问:instanceof 关键字你知多少?

基本概念和用途

instanceof 关键字在编程中(尤其是在Java和JavaScript中)用于检查一个对象是否是特定类(或接口、抽象类)的实例,或者是否属于该类的子类(或实现类)的实例。其返回值为布尔类型(true或false)。

Java中的用法:
在Java中,instanceof 主要用于确保在运行时对象可以被正确处理,特别是在进行类型转换之前,以避免ClassCastException。JavaScript中的用法:
在JavaScript中,instanceof 用于检查对象是否存在于某个构造函数的原型链上。

示例
示例1:Java中的instanceof用法

假设我们有一个类层次结构,包括一个基类 Animal 和其子类 Dog 和 Cat。

java
class Animal {
void sound() {
System.out.println(“Animal makes a sound”);
}
}

class Dog extends Animal {
void sound() {
System.out.println(“Dog barks”);
}
}

class Cat extends Animal {
void sound() {
System.out.println(“Cat meows”);
}
}

public class TestInstanceof {
public static void main(String[] args) {
Animal a = new Dog();
Animal b = new Cat();

    // instanceof 用法  if (a instanceof Dog) {  System.out.println("a is an instance of Dog");  } else {  System.out.println("a is not an instance of Dog");  }  if (b instanceof Cat) {  System.out.println("b is an instance of Cat");  } else {  System.out.println("b is not an instance of Cat");  }  // 检查基类  if (a instanceof Animal) {  System.out.println("a is an instance of Animal");  }  
}  

}

输出:

a is an instance of Dog
b is an instance of Cat
a is an instance of Animal

解释:

a 被创建为 Dog 对象,因此 a instanceof Dog 返回 true。
b 被创建为 Cat 对象,因此 b instanceof Cat 返回 true。
a 是 Animal 的子类 Dog 的实例,因此 a instanceof Animal 也返回 true。

示例2:JavaScript中的instanceof用法

在JavaScript中,我们可以使用instanceof来检查对象是否是某个构造函数的实例。

javascript
function Animal(name) {
this.name = name;
}

function Dog(name) {
Animal.call(this, name); // 调用父构造函数
}

Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

function Cat(name) {
Animal.call(this, name); // 调用父构造函数
}

Cat.prototype = Object.create(Animal.prototype);
Cat.prototype.constructor = Cat;

const a = new Dog(“Buddy”);
const b = new Cat(“Whiskers”);

// instanceof 用法
console.log(a instanceof Dog); // true
console.log(b instanceof Cat); // true
console.log(a instanceof Animal); // true
console.log(b instanceof Animal); // true

输出:

true
true
true
true

解释:

a 是 Dog 的实例,因此 a instanceof Dog 返回 true。
b 是 Cat 的实例,因此 b instanceof Cat 返回 true。
因为 Dog 和 Cat 的原型链上都包含 Animal,所以 a instanceof Animal 和 b instanceof Animal 都返回 true。

示例展示了instanceof在不同编程语言中用于类型检查的基本用法,希望可以帮助大家加深理解。


http://www.mrgr.cn/news/23301.html

相关文章:

  • PMP--一、二、三模--分类--14.敏捷--技巧--DoDDoR
  • 无人机视角-道路目标检测数据集 航拍 8600张 voc yolo
  • 使用Kimi生成Node-RED的代码
  • Python画笔案例-041 绘制正方形阶梯
  • 深度解析:云原生环境下Docker部署Doris数据库
  • Java | Leetcode Java题解之第395题至少有K个重复字符的最长子串
  • springboot后端开发-常见注解及其用途
  • C++ | Leetcode C++题解之第396题旋转图像
  • 联邦迁移学习
  • 深度学习模型常见评价指标准确率Accuracy、精确率Precision、召回率Recall、 F1分数F1 score分辨
  • 衡石分析平台使用手册-集群安装及启动
  • SAM 2:分割图像和视频中的任何内容
  • C++第二节入门 - 缺省参数和函数重载
  • OFDM系统PAPR算法的MATLAB仿真,对比SLM,PTS以及CAF,对比不同傅里叶变换长度
  • Linux 中的 data 命令介绍以及使用
  • Apple Intelligence深夜炸场!苹果发布4颗自研芯片,iPhone/iWatch/AirPods大升级
  • Android Manifest 权限描述大全对照表
  • 【经纬度坐标系、墨卡托投影坐标系和屏幕坐标系转换详解】
  • 顺序表之判空,删除
  • NISP 一级 | 2.5 安全审计