简体   繁体   English

为什么子类中的super.getClass()返回子类名

[英]why super.getClass() in a subclass returns subclass name

I am inside a subclass and when I am trying to find the name of super class, I tried super.getClass() , but it is returning me the name of the subclass only. 我在一个子类中,当我试图找到超类的名称时,我尝试了super.getClass(),但它只返回子类的名称。 Why? 为什么?

getClass().getSuperclass()应该这样做。

If you override a method from your superclass (or your superclass's superclass etc.), super.theMethod() will invoke the original method instead of the one you overrode it with. 如果你从你的超类(或你的超类的超类等)覆盖一个方法, super.theMethod()将调用原始方法而不是你用它覆盖的方法。 If you did not actual override theMethod , super.theMethod() will act exactly like theMethod() . 如果你没有实际覆盖theMethodsuper.theMethod()将完全像theMethod()

In this case I assume you did not override getClass() (in fact I know you didn't because it's final), so super.getClass() acts exactly like getClass() , ie either way the getClass method of the Object class is called. 在这种情况下,我假设你没有覆盖getClass() (实际上我知道你没有,因为它是最终的),所以super.getClass()行为与getClass()完全相同,即Object类的getClass方法的任何一种方式都是调用。

这是因为你正在创建派生类的对象而不是超类。你可以试试这个

this.getClass().getSuperClass();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM