feder
feder

Reputation: 1795

How to extend the generic class properly?

My question is a generic syntax question. As answered in this thread, I created the abstract generic super class.

public abstract class Translator <T extends OriginalText, V extends LanguageTranslation> {            
    public abstract V translate(T originalText);
}

Now, I fail in defining the child class.

public class ChineseToEnglishTranslator extends Translator<ChineseText, EnglishTranslation> {
    @Override
    public EnglishTranslation translate(ChineseText text) {
        return null;
    } 
}

Eclipse returns the error: Bound mismatch: The type ChineseText is not a valid substitute for the bounded parameter <T extends OriginalText> of the type Translator<T,V>. ChineseText is definitely a child class of OriginalText. What is the syntax of what I want to do?

Upvotes: 0

Views: 80

Answers (2)

Maxim Shoustin
Maxim Shoustin

Reputation: 77904

Since ChineseText is child of OriginalText and EnglishTranslation is child of LanguageTranslation, the Translator class that uses wildcard extends allows to all classes <? extends OriginalText> to use Translator. By the same way for LanguageTranslation

EnglishTranslation

public class EnglishTranslation extends LanguageTranslation{

}

ChineseText

public class ChineseText extends OriginalText{

}

OriginalText

public class OriginalText {

}

LanguageTranslation

public class LanguageTranslation {

}

ChineseToEnglishTranslator

public class ChineseToEnglishTranslator extends Translator<ChineseText, EnglishTranslation> {

@Override
public EnglishTranslation translate(ChineseText originalText) {
    return null;
}  
}

Upvotes: 2

TheKojuEffect
TheKojuEffect

Reputation: 21081

Make sure ChineseText extends OriginalText.

I'm not getting any errors as you have said if ChineseText extends OriginalText.

Bound mismatch: The type ChineseText is not a valid substitute for the bounded parameter of the type Translator.

This error appears only when ChineseText doesn't extends OriginalText.

Upvotes: 2

Related Questions