Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why extending an Interface does not make it's method to return more precise types?

For example if we have a class Person and a class Student extends Person. The we may have:

public interface PersonQueryBuilder<T extends Person> {
    PersonQueryBuilder<T> withName(String name);

    PersonQueryBuilder<T> withAgeBetween(int from, int to);

    List<T> getResultList();
}

public interface StudentRepository<T extends Student> extends PersonQueryBuilder<T> {
    StudentRepository studying(Course course);
}

So why when I have an StudentRepository, both the withName() and withAgeBetween() methods return a PersonQueryBuilder and not and StudentRepository? This is very annoying. Is there any "elegant" way of solving this problem?

like image 768
GuidoMB Avatar asked Sep 13 '26 18:09

GuidoMB


1 Answers

interface StudentRepository<T extends Student> extends PersonQueryBuilder<T> {
   StudentRepository<T> studying(Course course);
   StudentRepository<T> withName(String name);
   StudentRepository<T> withAgeBetween(int from, int to);
}

You can redeclare the methods in the sub-interface. Implementors of StudentRepository will now be required to return a StudentRepository for those methods, but the implementation can still be used polymorphically as a PersonQueryBuilder.

like image 142
Mark Peters Avatar answered Sep 16 '26 08:09

Mark Peters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!