I have many interfaces (Foo
and Bar
), abstract classes implementing those interfaces (AbstractFoo
and AbstractBar
), and classes extending those abstract classes (FooImpl1
, FooImpl2
, BarImpl1
and BarImpl2
). The interfaces are generics and parameters are pointing each others. Everything is compiling until I use a method from a generic field in the constructor of AbstractBar
class (this.foo.addBar(this);
).
class Main {
public static void main(String[] args) {}
interface Foo<B extends Bar> {
Set<B> getBars();
}
abstract class AbstractFoo<B extends AbstractBar> implements Foo<B> {
private final Set<B> bars = new HashSet<>();
public void addBar(B bar) {
this.bars.add(bar);
}
@Override
public Set<B> getBars() {
return this.bars;
}
}
class FooImpl1 extends AbstractFoo<BarImpl1> {}
class FooImpl2 extends AbstractFoo<BarImpl2> {}
interface Bar<F extends Foo> {
F getFoo();
}
abstract class AbstractBar<F extends AbstractFoo<?>> implements Bar<F> {
private final F foo;
public AbstractBar(F foo) {
this.foo = foo;
// this following line is breaking my head...
this.foo.addBar(this);
}
@Override
public F getFoo() {
return this.foo;
}
}
class BarImpl1 extends AbstractBar<FooImpl1> {
public BarImpl1(FooImpl1 foo) {
super(foo);
}
}
class BarImpl2 extends AbstractBar<FooImpl2> {
public BarImpl2(FooImpl2 foo) {
super(foo);
}
}
}