In Java super.getClass() prints an unexpected name in the derived class - why is that? [duplicate]

谁说我不能喝 提交于 2021-02-08 10:08:02

问题


Could you help me understand what gets printed in the code below System.out.println(super.getClass().getName());?

I see "PrintSubClass3" printed, even when I have mentioned super.

class PrintClass {
    int x = 0;
    int y = 1;
    void printMe() {
        System.out.println("X is " + x + ", Y is " + y);
        System.out.println("I am an instance of the class " +super.getClass().getName());
    }
}

class PrintSubClass3 extends PrintClass {
    int z = 3;
    void printMe() {
        System.out.println("x is " + x + ", y is " + y + ", z is " + z);
        System.out.println(super.getClass().getName());
        super.printMe();
    }
    public static void main (String args[]) {
        PrintSubClass3 obj = new PrintSubClass3();
        obj.printMe();
    }
}

回答1:


super.getClass() calls the method getClass() as defined by the parent class (ignoring any getClass method you may have defined in the class itself -- not sure if that is even possible with getClass, probably final).

This ends up calling Object#getClass, which returns the runtime class of the instance (which is what it is, an instance of PrintSubClass3).

All super does is let you call into the implementation of methods that you could otherwise not reach because you have overridden them. Here, it is redundant, as this.getClass() and super.getClass() end up at the same method.




回答2:


getClass() method returns the runtime class of this Object. In another words, your obj object, which is the object of class name PrintSubClass3 . So because of that, it will return PrintSubClass3.

so calling inside your class, it will give you its own class, even though there is super keyword. there is super keyword, it will go to its superClass for finding the method getClass(), but since its not implemented explicitly in superClass, getClass() method will work as documentation says ~ it will return runtime class of the object.

If you really want to print your superClass's name you should do this

 System.out.println(super.getClass().getSuperclass()); 

I hope this will clear your confusion.

what is the ideal way to print name of the class?

simply type this (you can print without super keyword )

     System.out.println(getClass().getName());   //Prints your local class
      System.out.println(getClass().getSuperclass()); //Prints your superClass


来源:https://stackoverflow.com/questions/34893848/in-java-super-getclass-prints-an-unexpected-name-in-the-derived-class-why-is

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!