如何在子类对象上调用超类方法?

时间:2016-09-14 18:48:50

标签: java generics inheritance compiler-errors

我有MySuperClassMySubClassMain

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 
} 

为什么呢?我指定了T extends MySuperClass。因此,所有MySuperClass方法都应该适用于子类。如何从子类对象中调用超类的方法?

1 个答案:

答案 0 :(得分:4)

subClassObject不是MySuperClass个实例,它是java.lang.Class个实例。您应该将此参数定义为T,而不是Class<T>以获得所需的行为:

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