How do you use a generic type as return value and

2020-04-20 09:56发布

问题:

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.

回答1:

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)


标签: java generics