How do I enforce that the method getFoo() in the implementing class, returns a list of the type of same implementing class.
public interface Bar{
....
List<? extends Bar> getFoo();
}
Right now a class that implements Bar returns objects of any class that implements Bar. I want to make it stricter so that the class that implements Bar returns a List of objects of only its type in getFoo().
Unfortunately this cannot be enforced by Java's type system.
You can get pretty close, though, by using:
public interface Bar<T extends Bar<T>> {
List<T> getFoo();
}
And then your implementing classes can implement it like so:
public class SomeSpecificBar implements Bar<SomeSpecificBar> {
// Compiler will enforce the type here
@Override
public List<SomeSpecificBar> getFoo() {
// ...
}
}
But nothing stops another class from doing this:
public class EvilBar implements Bar<SomeSpecificBar> {
// The compiler's perfectly OK with this
@Override
public List<SomeSpecificBar> getFoo() {
// ...
}
}
This is not possible in Java, but you might wonder what the use-case is to force this in the interface.
List<itself>
. And since you program against that specific class, the compiler has access to that specific return type and knows about itIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With