instanceof关键字简介
instanceof是Java中的一个关键字,用于测试一个对象是否是某个类的实例,或是否实现了某个接口。这个操作符返回一个布尔值(true或false),表示对象是否是指定类型的实例。
使用instanceof的基本语法:
object instanceof ClassName
其中,object是你要检查的对象。
ClassName是你想要检查的类或接口
instanceof的规则
- 对象与类型匹配:如果object是ClassName类型或其子类/实现类的实例,则返回true。
- 空值检查:如果object是null,则instanceof永远返回false。
- 接口检查:如果object 实现了ClassName接口,也会返回true。
代码示例:
package oneHundredDayPlan.threeDay;
class Animal {
public void makeSound() {
System.out.println("Some sound");
}
}
class Dog extends Animal {
public void bark() {
System.out.println("Woof");
}
}
class Cat extends Animal {
public void meow() {
System.out.println("Meow");
}
}
public class Main {
public static void main(String[] args) {
Animal dog = new Dog(); // 创建一个 Dog 实例
Animal cat = new Cat(); // 创建一个 Cat 实例
// 使用 instanceof 检查对象类型
System.out.println(dog instanceof Dog); // 输出 true
System.out.println(dog instanceof Animal); // 输出 true
System.out.println(dog instanceof Cat); // 输出 false
System.out.println(cat instanceof Cat); // 输出 true
System.out.println(cat instanceof Animal); // 输出 true
System.out.println(cat instanceof Dog); // 输出 false
System.out.println(null instanceof Cat);// 输出 false
}
}