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!
baz()can't returnClass? Did you try?bazto return aClass, or aClass<T, U>once the rawness has been eliminated. (I know it's just an example, but it's a poor choice of class name due to the existingjava.lang.Classclass.)Classwas because of overloading problems. The actual reason is because in my actual implementation, thebaz()function is implemented in an abstract class betweenInterfaceandClass, so even if it were to returnAbstractClass, this would not be enough of a downcast forClassto use. Thank you for the suggestion @rgettman, the reason I have not used return type covariance is because it is not an easily extensible solution for multiple inheriting layers of concrete classes