在 Java 中 super.getClass() 在派生类中打印了一个意外的名称 - 为什么会这样? [英] In Java super.getClass() prints an unexpected name in the derived class - why is that?

查看:21
本文介绍了在 Java 中 super.getClass() 在派生类中打印了一个意外的名称 - 为什么会这样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你能帮我理解下面的代码打印了什么System.out.println(super.getClass().getName());?

我看到打印了 "PrintSubClass3",即使我提到了 super.

class PrintClass {整数 x = 0;int y = 1;无效的打印我(){System.out.println("X 为" + x + ", Y 为" + y);System.out.println("我是类的一个实例" +super.getClass().getName());}}class PrintSubClass3 扩展 PrintClass {整数 z = 3;无效的打印我(){System.out.println("x 为" + x + ", y 为" + y + ", z 为" + z);System.out.println(super.getClass().getName());super.printMe();}公共静态无效主(字符串参数[]){PrintSubClass3 obj = new PrintSubClass3();obj.printMe();}}

解决方案

super.getClass() 调用父类定义的方法 getClass()(忽略您可能在类本身中定义的任何 getClass 方法 - 不确定是否可以使用 getClass,可能是 final).

这最终会调用 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() 在派生类中打印了一个意外的名称 - 为什么会这样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆