考虑这段代码
class Parent {
}
class Child extends Parent {
}
public class InheritenceExample {
public static void main(String[] args){
Parent p1 = new Child();
System.out.println("the class name is "+ p1.getClass().getName());
}
}
我声明p1为 of type Parent,但将其分配给 a Child instance。当我这样做时,getClass().getName()我得到Child了输出。在这种情况下,如何获得声明的类型Parent?
编辑:这并不适用于所有情况:getClass().getSuperclass().getName()
考虑这段代码
class Parent {
}
class Child extends Parent {
}
class GrandChild extends Child {
}
public class InheritenceExample {
public static void main(String[] args){
Parent p1 = new GrandChild();
System.out.println("the class name is "+ p1.getClass().getSuperclass().getName());
}
}
这输出Child,但它必须是Parent