// 定义一个父类
class Animal {
public void makeSound() {
System.out.println("Some generic animal sound");
}
}
// 定义一个子类
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Bark");
}
}
public class InstanceofExample {
public static void main(String[] args) {
Animal myDog = new Dog();
Animal myAnimal = new Animal();
// 使用 instanceof 检查对象的类型
if (myDog instanceof Dog) {
System.out.println("myDog is a Dog");
} else {
System.out.println("myDog is not a Dog");
}
if (myAnimal instanceof Dog) {
System.out.println("myAnimal is a Dog");
} else {
System.out.println("myAnimal is not a Dog");
}
}
}
instanceof 是 Java 中的一个关键字,用于检查对象是否是指定类型或其子类型的实例。Animal 和 Dog,其中 Dog 继承自 Animal。Animal 类型的引用变量 myDog 和 myAnimal,但它们指向的对象不同:myDog 指向的是 Dog 对象,而 myAnimal 指向的是 Animal 对象。instanceof 操作符来检查 myDog 和 myAnimal 是否是 Dog 类型的实例。结果会输出:myDog is a DogmyAnimal is not a Dog下一篇:java json转对象
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站