Java generics with typed container/containment relationships between two classes
I am hoping to produce some base classes that will include something like the following
class Container<T extends Containee>
{
T containee;
public T getContents(){return containee;}
public void setContents(T contents){ containee = contents; containee.setContainer(this); }
}
class Containee<T extends Container>
{
T container;
public T getContainer(){return container;}
public void setContainer(T container){this.container = container;}
}
There is a circular definition problem here which I thought I could ease using wildcards
class Container<T extends Containee<?>>
class Containee<T extends Container<?>>
except that the compiler complains about containee.setContainer(this)
. I have hacked a couple of ad-hoc solutions that will get the super-classes to compile, but nothing that will work for sub-classes, e.g.
class Foo extends Container<Bar>
class Bar extends Containee<Foo>
The generics tutorial and FAQ didn't seem to have anything obvious relating to th开发者_如何学Cis. How does one express such a relationship using generics?
Thanks
Perhaps something like:
abstract class Container<
THIS extends Container<THIS, T>,
T extends Containee<T, THIS>
> {
T containee;
protected abstract THIS getThis();
public T getContents() {
return containee;
}
public void setContents(T contents){
containee = contents;
containee.setContainer(getThis());
}
}
class Containee<
THIS extends Containee<THIS, T>,
T extends Container<T, THIS>
> {
T container;
public T getContainer() {
return container;
}
public void setContainer(T container) {
this.container = container;
}
}
(Or perhaps something with less generics.)
Try this:
class Container<T extends Containee<Container<T>>>
{
T containee;
public T getContents(){return containee;}
public void setContents(T contents){ containee = contents; containee.setContainer(this); }
}
class Containee<T extends Container<? extends Containee<T>>>
{
T container;
public T getContainer(){return container;}
public void setContainer(T container){this.container = container;}
}
class Bar extends Containee<Container<Bar>> {
}
class Foo extends Container<Bar> {
}
Foo now is a container accepting Bar objects whereas Bar would be addable to any container extending Container, so this would be possible as well:
class Baz extends Container<Bar> {
}
Baz is a container for Bar objects, too.
Would this be better with plain old polymorphism?
class Container
{
Containee containee;
public Containee getContents(){return containee;}
public void setContents(Containee contents){ containee = contents; containee.setContainer(this); }
}
class Containee
{
Container container;
public Container getContainer(){return container;}
public void setContainer(Container container){this.container = container;}
}
what is the problem with your first solution?
class Container<T extends Containee>
class Containee<T extends Container>
精彩评论