john john - 2 months ago 18
Java Question

How to call a superclass method on a subclass object?

I have a

MySuperClass
,
MySubClass
and
Main
classes

MySuperClass.java

public abstract MySuperClass {
String param;

public String getParam() {
return param;
}
}


MySubClass.java

public class MySubClass extends MySuperClass {
}


Main.java

public <T extends MySuperClass> void doWork (Class <T> subClassObject) {
subClassObject.getParam(); // method undefined
}


Why? I specified
T extends MySuperClass
. So all
MySuperClass
method should work for the subclass. How to call a superclass's method from a subclass object?

Answer

subClassObject is not a MySuperClass instance, it's a java.lang.Class instance. You should define this parameter as T, not as Class<T> to get the behavior you want:

public <T extends MySuperClass> void doWork (T subClassObject) {
   subClassObject.getParam();
   // etc...
}