dimanche 7 avril 2019

How to make "generic method declaration" to accept subclasses

I have a interface method:

List<User> getUsers(Query query);

and its implementation:

List<User> getUsers(Query query){
..
return users;
}

I can use it without problems:

Query q = new Query(..);
List<User> users = getUsers(q);

Now I create a subclass of Query:

class UserQuery extens Query{..}

and want to pass an instance of this subclass into getUsers()-method:

Query uq = new UserQuery(..);
List<User> users = getUsers(uq); // does not work, as getUsers accepts only "Query"-objects

As defined in the interface, getUsers() only accepts a "Query"-object and not its subclass.

How can I make the method more generic, so it can accepts Query-Objects but also all its subclasses ?

I tried this, but it is not possible in Java:

Interface:

// is not possible in java
List<User> getUsers(<E extends Query> query);

// also not possible in java
List<User> getUsers(Object<? extends MarketdataQuery> query);

Implementation:

// is not possible in java
List<User> getUsers(<E extends Query> query){
..
return users;
}

Aucun commentaire:

Enregistrer un commentaire