Imagine a generic class MySet which maintains a parent MySet instance and a child MySet instance. The idea is that the parent should be able to hold a superset of T and the child a subset. So given the following sample, consider the following problem:
class MySet<T> {
MySet<? extends T> child;
void doStuff (Collection<? extends T> args) {
child.doStuff(this, args);
}
}
EDIT: fixed question and sample code to reflect the real problem
Now, the child generic <T
> may be more restrictive than the parent's <T
>, so the parent must pass in a Collection<X
> where <X
> conforms to the child's <T
>. Keep in mind that this parent->child chain could extend to be arbitrarily long. Is there any way to arrange the generics so that parent.doStuff(...) will compile, ie, so that it can only be called with the arguments of it's most restrictive child?
This would mean that the java compiler would pass up generic information all the way up the parent->child chain to determine what the allowable arguments to doStuff could be, and I don't know if it has that capability.
Is the only solution to ensure children cannot be more restrictive than their parents using generics (ie, MySet<T
> child; rather than MySet<? extends T
>) and have children be more restrictive than their parents elsewhere in the code?