Java generics explanation needed

There are several simple test classes:

public interface ListCriteria<T> {
  // some stuff here
}

public class UserListCriteria implements ListCriteria<User> {
 // implementation
}

public interface Editor<T> {
  // sample method 1
  List<T> listObjectsTest1(ListCriteria<T> criteria);
  // sample method 2
  <L extends ListCriteria<T>> List<T> listObjectsTest2(L criteria);
}

And there is an implementation Editorthat Java believes that it does not provide the necessary implementation for both sample methods:

public class UserEditor implements Editor<User> {

  @Override
  public List<User> listObjectsTest1(UserListCriteria criteria) {
    //
  }

  @Override
  public List<User> listObjectsTest2(UserListCriteria criteria) {
    //
  }
}

Both implementations of the method are incorrect. The question is why. Especially for the last method. Of course, I could do it interface Editor<T, L extends ListCriteria<T>>, and that would solve the problem, but I do not want, I want to understand why I can not use generics at the method level here.

+4
source share
2 answers

The errors you get have nothing to do with generics, because you implement the method with a different type than the interface applies.

Interface Editordefines

List<T> listObjectsTest1(ListCriteria<T> criteria);

, UserEditor

public List<User> listObjectsTest1(ListCriteria<User> criteria) {

generic type. Editor ListCriteria. ListCriteria T T , implements ListCriteria<User>. , , ", , ".

,

public interface Editor<C, T extends ListCriteria<C>> {
    List<C> listObjectsTest1(T criteria);
}

UserEditor

public class UserEditor implements Editor<User, UserListCriteria> {

   public List<User> listObjectsTest1(UserListCriteria criteria) {
      return null;
   }
}

?

Editor

  <L extends ListCriteria<T>> List<T> listObjectsTest2(L criteria);

, L UserEditor

public <L extends ListCriteria<User>> List<User> listObjectsTest2(L criteria) {
    return null;
}

L, , . , , ListCriteria<User>.

+2
  • listObjectsTest1(UserListCriteria criteria) UserEditor listObjectsTest1(ListCriteria<T> criteria) Editor<T>, , .. .

  • listObjectsTest2, : <L extends ListCriteria<T>> List<T> listObjectsTest2(L criteria);, UserEditor : List<User> listObjectsTest2(UserListCriteria criteria)

, :

class UserEditor implements Editor<User> {


    @Override
    public List<User> listObjectsTest1(ListCriteria<User> criteria) {

    }

    @Override
    public <L extends ListCriteria<User>> List<User> listObjectsTest2(L criteria) {

    }
}

jls 8.4.8. , .

+1

All Articles