简体   繁体   中英

Using bounded wildcard when class has bounded type parameters

Suppose I have a class

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

and the class D with two classes extending it: B and C , eg

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?

Since T has an upper bound of D , A<?> is just a shorthand for A<? extends D> A<? extends D> . They both mean the same thing - just like if T were unbounded, A<?> would be short for A<? extends Object> 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> A<? extends D> immediately communicates the upper bound to a developer unfamiliar with A .

According to me you should go with A<? extends D>[] re; 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM