Ravi Rai Sharma
Ravi Rai Sharma

Reputation: 1

Java interface hierarchy and it's methods with bounded type Generics

I have a scenario where I found to build a hierarchy of type as follows:

IComponent (interface) -> AComponent (class)

Here I want IComponent to contain a method exeucte() which would be implemented by all the classes which implement this interface. Now, apart from the component hierarchy I also want a request/response format for all the components so I thought of below things:

IComponentRequest -> AComponentRequest

IComponentResponse -> IComponentResponse

Now I want to declare the execute() method in IComponent in such a way that all the classes which want to implement can follow the request and response classes of the above mentioned request/response hierarchy. Explaining in terms of code, I am currently declaring the method as below:

public interface IComponent<IComponentRequest,IComponentResponse> {

    IComponentResponse execute(IComponentRequest request);
}

What I actually want is something like :

<Any type which implements IComponentResponse> execute(<Any type which implements IComponentRequest> request) {
}

I tried using generics like :

public interface IComponent<REQUEST,RESPONSE> {} 

But in these cases I face issue in implementations while calling methods and receiving responses that REQUEST and RESPONSE are not any particular java types. Hence, I again went on to use the proper interfaces IComponentRequest and IComponentResponse but there I am not able to apply bounded generics.

Can someone please help on what am I missing here ?

Upvotes: 0

Views: 58

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201487

When you specify the generic name, you can also specify type information. Here, you want extends for each appropriate type. Something like

public interface IComponent<REQUEST extends IComponentRequest,
            RESPONSE extends IComponentResponse> {
    RESPONSE execute(REQUEST request);
}

Upvotes: 2

Related Questions