在初始化时设置泛型参数 - 在子类中

时间:2016-06-15 09:45:03

标签: java generics

我嗯,对于仿制药来说是新手,我在这里面临一个问题:

public class AnimationManager<STATE>{
    void loadAnimation(STATE state){
        //blahblah
    }
}

public class Unit{
    // AnimationManager<SomeType> animationManager; // I don't want this !!!
    AnimationManager animationManager; // i want it's type to be set in a subclass
}

public class MediumUnit extends Unit{
// nvm
}

public class FirstUnit extends MediumUnit{

    enum FirstUnitStates{
        S1, S2;
    }

    // i want to set it's type here, in subclasses (FirstUnit, SecondUnit etc.)
    public FirstUnit(){

        // this is ok, but It still doesn't have a type (it yells that I can remove the type from below statement)
        animationManager = new AnimationManager<FirstUnitStates>();

        // and now the problem - Unchecked call to loadAnimation(STATE) as a member of raw type.
        animationManager.loadAnimation(S1);
    }
}

这可以实现我的目标,没有类型铸造或类似的东西吗?制作通配符,对象类型?

我想让每个Unit(FirstUnit,SecondUnit)可以在AnimationManager中设置它自己的类型(将自己的状态存储在它的Enum中)。

修改

我编辑了我的问题,因为我在Unit和FirstUnit之间还有一个课程。 Nicolas Filotto解决方案是完美的,但它不适用于我的问题 - 我必须将参数从FirstUnit传递到MediumUnit并从MediumUnit传递到Unit - 它根本不起作用。

1 个答案:

答案 0 :(得分:2)

你应该做的是:

public class Unit<T> {
    AnimationManager<T> animationManager;

...

public class FirstUnit extends Unit<FirstUnitStates> {

响应更新:

这就是你需要简单地将MediumUnit作为下一个

进行参数化的想法
public class Unit<T> {
    AnimationManager<T> animationManager;

...

public class MediumUnit<T> extends Unit<T> {

...

public class FirstUnit extends MediumUnit<FirstUnitStates> {