Say I have an interface Interfacethat has a method aMethod() that should return itself, but also has a default implementation. Then I also have a class Foo that implements Interface and adds the additional method aFooMethod().
interface Interface {
public default Interface aMethod() {
// Some code
return this;
}
}
class Foo implements Interface {
public void aFooMethod() {
// Some code
}
}
Now I cannot call new Foo().aMethod().aFooMethod(); because aMethod() returns an Interface.
Now I could obviously go ahead and override the method in Foo:
class Foo implements Interface {
@Override
public Foo aMethod() {
Interface.super.aMethod();
return this;
}
public void aFooMethod() {
// Some code
}
}
The question I have is if there is a good way of forcing this, that a subclass has to return itself without it having to override that method?
My best aproach is to say something like this:
interface Interface<I extends Interface<I>> {
@SupressWarnings("unchecked")
public default I aMethod() {
// Some code
return (I)this;
}
}
But this is not what I would consider good as it has to use a SupressWarnings("unchecked"). Is there any better way?