Using bounded wildcard when class has bounded type parameters

287 views Asked by At

Suppose I have a class

public static class A<T extends D> { ... }

and the class D with two classes extending it: B and C, e.g.

public static class D { ... }
public static class B extends D { ... }
public static class C extends D { ... }

Now, at some place let's say I want an array of A's, irrespective of being of the B-kind or the C-kind. (And apply functions from class D to all items in the array, for example.)

Should I then constrain the type again?

In other words: which of these options is the one to go with?

  1. A<?>[] re;

  2. A<? extends D>[] re;

Which one is best practice?

2

There are 2 answers

0
Paul Bellora On BEST ANSWER

Since T has an upper bound of D, A<?> is just a shorthand for A<? extends D>. They both mean the same thing - just like if T were unbounded, A<?> would be short for A<? extends Object>.

I don't know of any best practice when it comes to this syntax; I think it's just a matter of coding style. I would prefer A<?> because it's concise, though A<? extends D> immediately communicates the upper bound to a developer unfamiliar with A.

4
Sachin On

According to me you should go with A<? extends D>[] re; So that user will not allow you to add only object which extends class D bounded wildcards provides limited flexibility within bound.

Any Type with bounded wildcards can only be instantiated within bound and any instantiation outside bound will result in compiler error.One of the important benefit of using bounded wildcard is that it not only restrict number of Type can be passed to any method as argument it also provides access to methods declared by bound. for example TreeMap(Comparator<? super K> comparator) allows access to compare() method of Comparator in Java.