Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 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 Reply

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...