My problem in a short and rather abstract form:
I would like to implement a Container
class which is type-parametrized by the Element
class type of the elements it contains (i.e. Container<T extends Element>
). Nothing really special so far. But: The Element
class and its sub-classes shall provide a register
method that adds the Element
instance to a given Container
class (i.e. register(Container<? super xxx> container) { ...}
)
I think this problem should be approachable in the following kind of way. However, the following code is not valid. In particular, the type parameters in ElementBasis#register
and Sub1Element#register
leads to name clash errors. Still I think it should be possible to find a proper implementation of that problem.
public interface Element {
void register(Container<T super Element> container);
}
public class ElementBasis {
@Override
void register(Container<? super ElementBasis> container) {
container.add(this);
}
}
public class Sub1Element extends ElementBasis {
// ...
@Override
void register(Container<? super Sub1Element> container) {
container.add(this);
}
}
public class Sub2Element extends ElementBasis {
// ...
}
Moreover, I would like to be able to give the elements a structure by providing an ElementGroup
sub-class of Element
:
public class ElementGroup<T extends Element> extends ElementBasis {
// ...
@Override
void register(Container<? super T> container) {
foreach(T member : groupMemebers) {
container.add(member)
}
}
}
I also tried to solve the problem by parametrizing the Element
classes such that its type parameter can be used in the register
method. Unfortunately with no success.
Can anyone find a proper implementation?