Consider this code
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());
}
}
I declare p1
to be of type Parent
, but assign it to a Child instance
. when I do getClass().getName()
I get Child
as output. how can I get the declared type which is Parent
in this case?
EDIT: This does not work in all cases: getClass().getSuperclass().getName()
consider this code
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());
}
}
This ouputs Child
but it must be Parent