2016-06-15 3 views
2

Я являюсь хмм, новым для дженериков, и я столкнулся с проблемой здесь:Установить общий параметр инициализации - в подклассе

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 (с его собственными состояниями, хранящимися в Enum).

Редактировать

Я отредактировал мой вопрос, потому что у меня есть еще один класс между блоком и FirstUnit. Решение Nicolas Filotto отлично, но оно не работает для моей проблемы - мне пришлось бы передать параметр от FirstUnit до MediumUnit и от MediumUnit к Unit - и он просто не работает.

+0

почему он не работает? это как сделать это в любом случае, это на самом деле по этой точной причине, что generics были созданы –

ответ

2

Что вы должны сделать это:

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

...

public class FirstUnit extends Unit<FirstUnitStates> { 

Update Response:

Это та же идея вам нужно будет просто параметризованных MediumUnit слишком в следующем

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

...

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

...

public class FirstUnit extends MediumUnit<FirstUnitStates> { 
+0

, и если у меня больше наследования, например Unit> BigUnit> MediumUnit> SmallUnit, и я хочу это в SmallUnit Мне нужно передать параметр в каждый из них, верно? –

+0

ответ обновлен –

+0

это прекрасно, спасибо! –

Смежные вопросы