The other day I wad trouble understand a particular textbook example related to bounded wildcards and how they're used in combination with a Queue.
The example starts by setting up a trivial inheritance hierarchy:
class X {
int i;
X(int i) { this.i = i; }
}
class Y extends X {
int i;
Y(int i){ this.i = i; }
}
class Z extends Y {
int i;
Z(int i) { this.i = i; }
}
The main class hosts a static method that takes a Queue with an upper-bounded wildcard definition and adds a random number of new elements.
public class Wildcards {
static void rtn(Queue<? extends Y> q) {
q.add(new Y(5));
q.add(new Z(5));
}
public static void main(String[] args) {
Queue<Y> q = new LinkedList<>();
rtn(q);
}
}
My understanding of this particular wildcard definition is "Allow adding elements to q
that are either of type Y or extend from type Y. So q.add(new Y(5))
would be as legal as q.add(new Z(5))
. However the compiler is complaining in both cases: Required type: capture of ? extends Y - Provided Y/Z
.
I'm struggling to understand this message in this context - I have a hunch that it might not be related to the wildcard definition at all but I'm not sure.
Thanks so much for your help!