开发者

Java Generics - are these two method declarations equivalent?

Given some class SomeBaseClass. Are these two method declarations equivalent?

pub开发者_开发知识库lic <T extends SomeBaseClass> void myMethod(T param) 

and

public void myMethod(<? extends SomeBaseClass> param)


No, these are not equivalent. The second won't even compile as it has no meaning (why would you use generics in that case anyway?)


As others have mentioned, ? extends SomeBaseClass is not a type and doesn't make sense there. However, you can really just put SomeBaseClass there, because anything that is an instance of a subclass of SomeBaseClass is, by inheritance, also an instance of SomeBaseClass.

So, from the perspective of someone calling these functions, (since T is only used once, and therefore has no constraining effect on other types), the following two are functionally equivalent:

public <T extends SomeBaseClass> void myMethod(T param)

and

public void myMethod(SomeBaseClass param)

Note, however, that these two will appear differently to reflection. Also, there might be some need inside the function for a generic type T, so the first form may be necessary in some cases (although one can still write a wrapper for it in the second form in this case).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜