I want to have a class which implements an interface, which specifies the specific subclass as a parameter.
public abstract Task implements TaskStatus<Task> { TaskStatus<T> listener; protected complete() { // ugly, unsafe cast callback.complete((T) this); } } public interface TaskStatus<T> { public void complete(T task); }
But instead of just task, or , I want to guarantee the type-arg used is that of the specific class extending this one.
So the best I’ve come up with is:
public abstract Task<T extends Task> implements TaskStatus<T> { }
You’d extend that by writing:
public class MyTask extends Task<MyTask> { }
But this would also be valid:
public class MyTask extends Task<SomeOtherTask> { }
And the invocation of callback will blow up with ClassCastException. So, is this approach just wrong and broken, or is there a right way to do this I’ve somehow missed?
It is not clear what you are trying to do inside of
Task. However, if you define the generic classTask<T>as follows:The following two are possible:
But the following is prohibited:
The above definition of
Taskuses F-bounded polymorphism, a rather advanced feature. You can check the research paper ‘F-bounded polymorphism for object-oriented programming‘ for more information.