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?
Asked
Active
Viewed 6,070 times
12
-
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 Answers
11
getClass().getSuperclass()
should do.

Bozho
- 588,226
- 146
- 1,060
- 1,140
-
http://stackoverflow.com/questions/3294656/how-to-get-the-parent-base-class-object-super-getclass this thread by you suggested of Bad Design , so what will be your recommendation to avoid it – Abhishek Choudhary Mar 20 '12 at 16:00
-
-
My recommendation would be to avoid reflection altogether if possible. – Louis Wasserman Mar 20 '12 at 17:27
-
as a general rule - yes, but it is applicable in a limited set of scenarios – Bozho Mar 20 '12 at 20:45
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