This is a bit of a lazyweb question but you get the rep so 🙂
I have a Java class that returns instances of itself to allow chaining (e.g. ClassObject.doStuff().doStuff())
For instance:
public class Chainer { public Chainer doStuff() { /* Do stuff ... */ return this; } }
I would like to extend this class. Is there a way, perhaps using generics, to extend this class without having to overwrite each method signature?
E.g. not:
public class ChainerExtender extends Chainer { public ChainerExtender doStuff() { super.doStuff(); return this; } }
I have tried:
public class Chainer { public <A extends Chainer> A doStuff() { /* Do stuff ... */ return (A)this; } } public class ChainerExtender extends Chainer { public <A extends Chainer> A doStuff() { /* Do stuff ... */ return super.doStuff(); } }
But this didn’t work giving the error:
type parameters of <A>A cannot be determined; no unique maximal instance exists for type variable A with upper bounds A,Chainer
Am I forced to have class declarations like:
public class Chainer<T extends Chainer<T>> {} public class ChainerExtender extends Chainer<ChainerExtender>
As per this question?
Have you tried the straight-forward
With Java 5, you can declare overriding methods to have co-variant return types, which means just what this says: a subclass can have an overriding method signature with a more specific return type.