我是嗯,泛型新手,我在这里面临一个问题:
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);
}
}
如果没有类型转换或类似的东西,这可以实现我的目标吗?制作通配符,对象类型?
我想让每个单元(FirstUnit、SecondUnit)都可以在 AnimationManager 中设置自己的类型(将自己的状态存储在枚举中)。
编辑
我编辑了我的问题,因为我在 Unit 和 FirstUnit 之间多了一个类。 Nicolas Filotto 解决方案很完美,但它不适用于我的问题 - 我必须将参数从 FirstUnit 传递到 MediumUnit,再从 MediumUnit 传递到 Unit - 而且它根本不起作用。
最佳答案
你应该做的是:
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> {
关于java - 在初始化时设置通用参数 - 在子类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37831796/