简体   繁体   中英

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:

UserQuery 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;
}

**

EDIT:

**

It works only when I pass a "Query"-Object:

// This works: 
Query q = new UserQuery(..); 
List<User> users = getUsers(q);


// This does not work:
UserQuery uq = new UserQuery(..);
List<User> users = getUsers(uq);

The get the actual Query-Object, I have to use a cast, so I cannot pass a UserQuery into the method..

List<User> getUsers(Query query){
    UserQuery uq = (UserQuery) query;
    return users;
}

You can generify method, not only the parameter. This will do the work:

<E extends Query> List<User> getUsers(E query);

Now query can be of type Query or any other subclass of it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM