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?
You can use an upper bounded wildcard to relax the restrictions on a variable. For example, say you want to write a method that works on List<Integer>, List<Double>, and List<Number>; you can achieve this by using an upper bounded wildcard.
Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class. These are known as bounded-types in generics in Java.
To declare a bounded type parameter, list the type parameter's name, followed by the extends keyword, followed by its upper bound, which in this example is Number . Note that, in this context, extends is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces).
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.
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With