Udo
Udo

Reputation: 2387

Java Generics - are these two method declarations equivalent?

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

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

and

public void myMethod(<? extends SomeBaseClass> param)

Upvotes: 2

Views: 121

Answers (2)

newacct
newacct

Reputation: 122449

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).

Upvotes: 0

Michael Borgwardt
Michael Borgwardt

Reputation: 346307

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?)

Upvotes: 5

Related Questions