Duplicate :
|
|
Relates :
|
|
Relates :
|
|
Relates :
|
A DESCRIPTION OF THE REQUEST : The SelfType pattern (which goes by many names, and is closely related to the problem described in closed bug 6431633), in concept, is extremely useful for more sophisticated applications of generics. The SelfType pattern in reality is a limited workaround for situations requiring the use the type of THIS class in the class definition. It takes the familiar form... abstract class AbstractClass<THIS extends AbstractClass<THIS>> { abstract public THIS getThis(); public void setPeer(THIS peer) {_peer = peer;} private THIS _peer; } class ConcreteClass extends AbstractClass<ConcreteClass> { public ConcreteClass getThis() {return this;} } Unfortunately, concrete classes, such as ConcreteClass cannot be extended with "this-awareness". Thus... class ConcreteSubClass extends ConcreteClass {} ConcreteClass obj = new ConcreteClass(); ConcreteSubClass subobj = new ConcreteSubClass(); subobj.setPeer(obj); // !!!should be an error, but thisness is lost The problem becomes even worse if you want two this-aware generic classes that mutually reference one another... public abstract class AbstractPeer<THIS extends AbstractPeer<THIS,THAT>, THAT extends AbstractPeer<THAT,THIS>> { public void setPeer(THAT peer) { _peer = peer; // this references that _peer.setPeer(getThis()); // that references this } public THAT getPeer() { return _peer; } public abstract THIS getThis(); private THAT _peer; } public class AlphaPeer<THAT extends BetaPeer<AlphaPeer<THAT>>> extends AbstractPeer<AlphaPeer<THAT>,THAT> { // !!!does not compile public AlphaPeer<THAT> getThis() { return this; } } public class BetaPeer<THAT extends AlphaPeer<BetaPeer<THAT>>> extends AbstractPeer<BetaPeer<THAT>,THAT> { // !!!does not compile public BetaPeer<THAT> getThis() { return this; } } JUSTIFICATION : Imagine if the java language spec were to say that a concrete class could only be extended once. Without some inherent support for a THIS type, that is essentially what is happening (and a lot more) in more sophisticated attempts at employing generics for code reusability. EXPECTED VERSUS ACTUAL BEHAVIOR : EXPECTED - A robust this-awareness in generic classes, where concrete classes can be correctly extended, and where mutual references can be properly defined ACTUAL - A wimpy this-awareness in generic classes, which relies on generic constructs approaching the level of hieroglyphics (Foo<THIS extends Foo<THIS>)
|