I have (for me) a difficult issue with Java generics. I read some documents and understood some, but, of course, not everything I need. Basically, for me, trying to solve this will lead to an attempt and an error.
Next, I give a concise example of my code once without any generics (so you can hope to understand what I want to achieve), and the other with some additions that come close to the solution. Please correct my second version and / or provide me with specific documentation. (I have general documentation on Java generics. But my code seems to have a few hurdles, and this is difficult for a proper solution)
In my example: there is an abstract base type and several implementation options (only one is provided). The combine() method calls getOp1() , which solves (depending on <some condition> ) if it should work on its own instance or on a new one. After calculation, the target instance is returned.
abstract class Base { protected final Base getOp1() { if(Util.isConditionMet()) { return getNewInstance(); } else { return this; } } protected abstract Base getNewInstance();
Added version with some generics. This version is malfunctioning and does not compile.
abstract class Base<T extends Base<T>> { protected final T getOp1() { if(Util.isConditionMet()) { return getNewInstance(); } else { return this; } } protected abstract T getNewInstance(); // returns a new instance of an implementing class public abstract T combine(T other); } class Variant<T extends Variant<T>> extends Base<T> { protected T getNewInstance() { return new Variant(); } public T combine(T op2) { T op1 = getOp1(); op1.calculate(op2); return op1; } private void calculate(T other) { /* some code */ } }
source share