instanceof的使用

  • instanceof 在多态中是判断运行类型是否从属于 of后面的类的判断方法
Person p = new Student();  // 这里假设 Person 是父类,Student 是子类
if (p instanceof Person) { // p 的运行类型是Student,而Student是Person的子类,所以这里会输出
    System.out.println("p 是 Person 类型的实例");
}
if (p instanceof Student) {// p 的运行类型是Student,所以这里会输出
    System.out.println("p 是 Student 类型的实例");
}
  • 再举一个例子,假设有一个接口 Shape 和两个实现类 Circle 和 Rectangle,我们可以使用 instanceof 操作符来判断一个对象是否实现了 Shape 接口:
Shape shape = new Circle();  // 创建一个 Circle 类型的对象,并将其赋值给 Shape 类型的变量
if (shape instanceof Shape) {
    System.out.println("shape 实现了 Shape 接口");
}
if (shape instanceof Rectangle) {
    System.out.println("shape 是 Rectangle 类型的实例");
}
  • 上面的代码中,我们创建了一个 Circle 类型的对象,并将其赋值给 Shape 类型的变量 shape。使用 instanceof 操作符来判断 shape 是否实现了 Shape 接口和 Rectangle 类型的实例。由于 Circle 类型的对象实现了 Shape 接口,因此第一个 if 语句输出;而由于 shape 不是 Rectangle 类型的实例,第二个 if 语句不会执行。

posted on   盗版太极  阅读(27)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示