I have an interface with a function that currently returns itself. However, I would like any implementation classes to instead return that class instead of the base interface. For example, in this simplified example, this works fine:
public interface MyInterface<T, U> {
public void foo(T t, U u);
public MyInterface baz();
}
public class MyClass<T, U> implements MyInterface<T, U> {
@Override
public void foo(T t, U u) {}
public MyClass bar() {
return this;
}
@Override
public MyInterface baz() {
return this;
}
}
But if I were to change the last function to this:
@Override
public MyClass baz() {
return this;
}
This fails, obviously, because the overriding function no longer matches the declaration in the interface.
The reason I need baz() to return Class instead of Interface is because the caller may call bar and baz an arbitrary number of times in an arbitrary order, but currently all bar() calls must be before all baz() calls, unless we repetitively downcast it.
What complicates this even more is the foo() function which uses two generic types. I looked into using curiously recurring generic patterns but was not able to find a reasonable solution because Interface already deals with generics, even without it.
Is there any way around this problem? Thanks!