このコードを検討してください
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
しますがtype Parent
、それを に割り当て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