multitaskPro
multitaskPro

Reputation: 571

Using generics that extend a class

I have a class like this:

public abstract class SomeClass<E extends AnotherClass> { 
    private E someVariable;

    public E formatVariable(){
        E formatted = someVariable.format(); //format is a method in AnotherClass, which returns AnotherClass
        return formatted;
    }
}

Eclipse gives me an error, it "cannot convert from AnotherClass to E"

I am confused because in the class decleration I made it so that E is AnotherClass or a subclass of it, or at least that was my understanding of it.

What's going on here, and how can I fix this error?

Upvotes: 0

Views: 40

Answers (1)

yshavit
yshavit

Reputation: 43436

format() returns AnotherClass, but you don't want just any AnotherClass — you want an E specifically. What if you had this?

public class AnotherClassRed extends AnotherClass {
    @Override
    public AnotherClass format() {
        return new AnotherClassBlack();
    }
}

public class AnotherClassBlack extends AnotherClass {
    // Note: This is *not* a subclass of AnotherClassRed
    ...

With that scenario, if things compiled then formatVariable() would return the formatted instance as AnotherClassRed, but the instance is actually an AnotherClassBlack; the result would be a ClassCastException.

It sounds like you want format() to return E, not AnotherClass.

Upvotes: 1

Related Questions