12

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. Why?

Abhishek Choudhary
  • 8,255
  • 19
  • 69
  • 128
  • Maybe add some code and sample output? – smessing Mar 20 '12 at 15:53
  • possible duplicate of [How to get the parent base class object super.getClass()](http://stackoverflow.com/questions/3294656/how-to-get-the-parent-base-class-object-super-getclass) – assylias Mar 20 '12 at 15:57

3 Answers3

11

getClass().getSuperclass() should do.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
5

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. If you did not actually override theMethod, super.theMethod() will act exactly like 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(), i.e. either way the getClass method of the Object class is called.

sepp2k
  • 363,768
  • 54
  • 674
  • 675
  • yes , I agree , but why such design , if super is being mentioned for calling the method , why it is not calling the super class method , – Abhishek Choudhary Mar 20 '12 at 16:02
  • 4
    @AbhishekChoudhary It is. When you call `getClass`, you're calling the method `getClass` defined in `Object`. `Object` is a superclass of your class (even if not the direct superclass), so you are calling the superclass's version of the method. In fact the superclass's version is the only version of that method. – sepp2k Mar 20 '12 at 16:04
0

This is because you are creating object of derived class and not super class.. you may try this

this.getClass().getSuperClass();
Mayur
  • 676
  • 8
  • 16