8

I have a method where I want to accept class types that must extend an abstract class. What is the difference between

<T extends AbstractClass> void myMethod(Class<T> clazz);

and

void myMethod(Class<? extends AbstractClass> clazz); ?

I wouldn't be able to directly reference the type inside the method in the second case. Is there any difference in which class types could be passed to these two methods?

joeblubaugh
  • 1,127
  • 7
  • 10
  • 2
    @prudhvi, the `` is a (bounded) type parameter, making the overall declaration that of a generic method. That's different from being a method of a generic class. – John Bollinger Apr 20 '15 at 18:30
  • @JohnBollinger I thought it should be either myMethod(Class clazz); or void myMethod(Class clazz); Am I right? – Prudhvi Apr 20 '15 at 18:32
  • 1
    *"Am I right?"* No you're not. The type parameter doesn't replace the return type. – Tom Apr 20 '15 at 18:53
  • 1
    @Tom Got it. I learned something new today. – Prudhvi Apr 20 '15 at 19:11

3 Answers3

5

No, there is no difference between the argument types compatible with the two method signatures you presented. Personally, I would use the parameterized version if I needed to reference the exact type represented by the argument, but otherwise I would use the wildcard version.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
2

In the 1st one you will also be able to return T (or any type parameterized with T: List<T>, Set<T> and so on...) , without needing to cast it

<T extends AbstractClass> T myMethod(Class<T> clazz);

And use it as :

Subclass parameterInstance =... 
Subclass i1 = myMethod(parameterInstance.getClass());
Yosef-at-Panaya
  • 676
  • 4
  • 13
1

This question has been asked many places, notably here and here.

Both questions deal primarily with unbounded wildcards and generic types but the same principles apply here. I'd also recommend reading one of the links (Angelika Langer - Java Generics FAQs) provided by one of the answers to the other questions (placed here for convenient).

Whilst in your specific case there is no difference, the difference comes down simply to how you would be dealing with the type data internally (within the method). Go with what seems to describe your purpose the best. If you are dealing with data of unknown type and you require the specific input type to be specifically usable within the method, you'll need to go with the generics approach. If on the other hand, you do not and can suffice with treating all input data as simply of the bounding type (e.g. AbstractClass in your case) you may go with the bounded wildcard approach.

Community
  • 1
  • 1
initramfs
  • 8,275
  • 2
  • 36
  • 58