membersound
membersound

Reputation: 86627

How to group different services to execute base logic?

I have an abstract superservice that should perform some common logic. Several services implement this superservice. I chose the ServiceImpl based on a condition, and want to assign it to the abstract type, for later running the common logic.

But I won't let me write typesafe code, so probably something in the design is wrong. How could I improve the following?

//superservice
abstract class AbstractService<T extends BaseResponse> {
    public void run() {
        //execute some common logic
    }
}

//implementations
class FirstService extends AbstractService<FirstResponse extends BaseResponse> {
}

class SecondService extends AbstractService<SecondResponse extends BaseResponse> {
}

usage:

//this works, but claims to have missing type argument, not being typesafe
AbstractService myservice = condition ? new FirstService() : new SecondService();
myservice.run();

----------------

//this will not compile with "type missmatch" hint
AbstractService<BaseResponse> myservice = condition ? new FirstService() : new SecondService();
myservice.run();

Upvotes: 0

Views: 37

Answers (1)

Adam Siemion
Adam Siemion

Reputation: 16029

To make it compile you need to change:

AbstractService<BaseResponse> myservice = condition ? 
    new FirstService() : new SecondService();

to:

AbstractService<? extends BaseResponse> myservice = condition ? 
    new FirstService() : new SecondService();

Upvotes: 2

Related Questions