0

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?

2
  • 4
    An E is an AnotherClass, but an AnotherClass is not necessarily an E. The result of format is an AnotherClass, but it isn't guaranteed to be an E. Commented Apr 22, 2016 at 0:06
  • @resueman That should be in the answers section Commented Apr 22, 2016 at 0:07

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the help, that makes sense. In my situation my method necessarily returns an object that is E, but that's because of other code within AnotherClass.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.