I try to create an abstract class with generics. The business logic is to translate a text from one language to another. There must be a Translator
class for each language. I also require a LanguageTranslation
class for each language, which is the return object of the translate
method, which takes on the parameter T
. That T is supposed to be of a sub class of OriginalText
(e.g. EnglishText, ChineseText, etc). And that is where I struggle. How do you code this constraint?
I've created the following super class.
public abstract class Translator <T, V> {
public abstract <V extends LanguageTranslation> V translate(T originalText);
}
If I misunderstand the concept of generics or apply it wrong, please illuminate. Thanks.
Just add it where you define your Generics :
public abstract class Translator <T extends OriginalText, V> {
public abstract <V extends LanguageTranslation> V translate(T originalText);
}
Btw, this is confusing because the V
definition is overriden in your method. Why not doing this :
public abstract class Translator <T extends OriginalText, V extends LanguageTranslation> {
public abstract V translate(T originalText);
}
EDIT: explaining why you have a warning on V
It's exactly the same as :
public abstract class Translator <T extends OriginalText, V> {
public abstract <K extends LanguageTranslation> K translate(T originalText);
}
Now inside the method you have 3 generics :
- K of runtime determined subtype of LanguageTranslation
- T of runtime determined subtype of OriginalText
- V runtime determined subtype of Object (default constraint)