Oren
Oren

Reputation: 4252

Overriding generic abstract method's return type without type safety warnings

In some SuperClass I have an abstract generic method:

protected abstract <T extends Foo> T getFoo();

In my SubClass I try to override it with:

@Override
protected SubFoo getFoo() {             
    return new SubFoo();
}

where public class SubFoo extends Foo

in my subclass's getFoo I get the following error.

"Type safety: The return type SubFoo for getFoo() from the type SubClass needs unchecked conversion to conform to T from the type SuperClass"

My questions are:

1) Is there any scenario where this is not safe ?

2) If not, shouldn't the compiler be able to figure that out ? what is preventing the compiler from figuring out that SubFoo is a subclass of Foo at compile time ?

3) Is there a way to achieve something like this, but warning free ?

Upvotes: 3

Views: 1174

Answers (1)

Louis Wasserman
Louis Wasserman

Reputation: 198103

Yes, this is unsafe and illegal. The SuperClass declaration you've written allows the caller -- not the SuperClass subclass -- to choose which subtype of Foo it wants, so your implementation in SubClass doesn't implement it properly.

Instead, you must have T as a generic parameter for SuperClass itself, not just the method: SuperClass<T extends Foo>, and then SubClass extends SuperClass<SubFoo>.

Upvotes: 9

Related Questions