Java instanceof 运算符:判断对象类型
以下是您提供的 Java 代码:
class Animal { }
class Dog extends Animal { }
public class Main {
public static void main(String[] args) {
Animal animal = new Dog();
if (animal instanceof Dog) {
System.out.println('It's a dog.');
} else {
System.out.println('It's not a dog.');
}
}
}
在这段代码中,if 语句的条件 animal instanceof Dog 将评估为真。这是因为我们创建了一个 Animal 类的引用 animal,并将其指向 Dog 类的实例。
由于 Dog 类是 Animal 类的子类,因此 animal instanceof Dog 将返回 true。
因此,运行这段代码将会输出:'It's a dog.'
原文地址: https://www.cveoy.top/t/topic/pSp 著作权归作者所有。请勿转载和采集!