这最终会调用 Object#getClass,它返回实例的运行时类(它是PrintSubClass3 的实例).super 所做的就是让您调用方法的实现,否则您无法访问这些方法,因为您已经覆盖了它们.在这里,它是多余的,因为 this.getClass() 和 super.getClass() 以相同的方法结束.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(); }} 解决方案 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. 这篇关于在 Java 中 super.getClass() 在派生类中打印了一个意外的名称 - 为什么会这样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-22 08:39