// 示例代码:使用 instanceof 检查对象类型
class Animal {
// 动物类
}
class Dog extends Animal {
// 狗类,继承自动物类
}
public class InstanceofExample {
public static void main(String[] args) {
Animal myDog = new Dog();
// 使用 instanceof 检查 myDog 是否是 Dog 类型
if (myDog instanceof Dog) {
System.out.println("myDog 是 Dog 类型");
} else {
System.out.println("myDog 不是 Dog 类型");
}
// 使用 instanceof 检查 myDog 是否是 Animal 类型
if (myDog instanceof Animal) {
System.out.println("myDog 是 Animal 类型");
} else {
System.out.println("myDog 不是 Animal 类型");
}
// 使用 instanceof 检查 null 对象
Animal myNullAnimal = null;
if (myNullAnimal instanceof Animal) {
System.out.println("myNullAnimal 是 Animal 类型");
} else {
System.out.println("myNullAnimal 不是 Animal 类型或为 null");
}
}
}
instanceof 关键字用于检查对象是否是指定类型或其子类的实例。myDog 是 Dog 类的实例,因此 myDog instanceof Dog 返回 true。Dog 继承自 Animal,所以 myDog instanceof Animal 也返回 true。null,instanceof 表达式总是返回 false。下一篇:java lambda排序
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站