Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

java - Overriding method with generic return type

Let's say I have a super-class that defines the following abstract method

public abstract <T extends Interface> Class<T> getMainClass();

Now if I want to override it in some sub-class

public Class<Implementation> getMainClass(){
    return Implementation.class;
}

I get a warning about type safety and unchecked conversion:

Type safety: The return type Class<Implementation> for getMainClass() from the type SubFoo needs unchecked conversion to conform to Class<Interface> from the type SuperFoo

Doesn't Class<Implementation> fall under Class<T> if <T extends Interface>? Is there any way to properly get rid of the warning?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

the overriding method's return type must be a subtype of the overridden method's return type.

Class<Impl> is not a subtype of Class<T> where <T extends Interface>. T is unknown here.

Class<Impl> is a subtype of Class<? extends Interface>, per subtyping rules.


some subtyping rules regarding wildcards:

for any type X

  • A<X> is a subtype of A<? extends X>

  • A<X> is a subtype of A<? super X>

if S is subtype of T

  • A<? extends S> is a subtype of A<? extends T>

  • A<? super T> is a subtype of A<? super S>

More concisely, ( <: means "is a subtype of" )

A<S>    <:    A<? extends S>    <:    A<? extends T>

A<T>    <:    A<?  super  T>    <:    A<?  super  S>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...