使用instanceof关键字在运行时动态判断实例的类型
Java的instance关键字可以实现"运行时类型识别"(Run-time type identification, RTTI)
Java的instance关键字可以实现"运行时类型识别"(Run-time type identification, RTTI),也就是说可以通过instanceof关键字判断某个对象是否时没个类的实例,例如:
class ClassA {
ClassA() {
}
}
class ClassB {
ClassB() {
}
}
public class MyInstanceOf {
public static void main(String[] args) {
sayClass(new ClassA());
sayClass(new ClassB());
}
public static void sayClass(Object o) {
if (o instanceof ClassA)
System.out.println("This is ClassA");
if (o instanceof ClassB)
System.out.println("This is ClassB");
}
}
输出结果:
This is ClassA
This is ClassB