0

All, I may have a basic misunderstand about the Generic in Java ,

Why can't we write a Java Generic son class to inherit its parent Generic class ?

define such as :

public class JsonResponse<T> implements Response {
}

But I define a another son class to inherit it :

public class MeetingClientResponse<T> extends JsonResponse<T> {
}

I define another caller class as:

public interface HttpExecutor<T extends Response> {
}

impl it class is :

public class DefaultHttpExecutor<T extends Response> implements HttpExecutor<T> {
       public DefaultHttpExecutor(ResponseHandler<T> responseHandler) {
    this.responseHandler = responseHandler;

}
}

public class JsonResponseHandler<T> implements ResponseHandler<JsonResponse<T>> {
}

public class ScheduleMeetingResponseHandler extends
    JsonResponseHandler<ScheduleMeetingResponseVO> {
}

handler = ScheduleMeetingResponseHandler.newIntance()

When I use like this , it is no compile error:

HttpExecutor<JsonResponse<ScheduleMeetingResponseVO>> httpExecutor = 
new DefaultHttpExecutor
         <JsonResponse<ScheduleMeetingResponseVO>>(handler);

But When I use like this , it will compile error in Eclipse :

HttpExecutor<MeetingClientResponse<ScheduleMeetingResponseVO>> httpExecutor = 
new DefaultHttpExecutor
          <MeetingClientResponse<ScheduleMeetingResponseVO>>(handler);

Eclipse tip error as : The Constructor DefaultHttpExecutor is undefined

Jerry Cai
  • 571
  • 2
  • 8
  • 18

2 Answers2

1

Declare your DefaultHttpExecutor constructor as

public DefaultHttpExecutor(ResponseHandler<? super T> responseHandler)

This is because you're trying to create a DefaultHttpExecutor for MeetingClientResponse, but you're passing to it a handler which is for JsonResponse.

With that declaration, you state that the executor will be able to work with a handler specific for MeetingClientResponse, or more generic handlers which can be satisfied with a supertype of the specific kind.

See also What is PECS (Producer Extends Consumer Super)?

Community
  • 1
  • 1
Flavio
  • 11,925
  • 3
  • 32
  • 36
0

The DefaultHttpExecutor<T> constructor expects a ResponseHandler<T> argument. More accurately, it expects an argument declared as a ResponseHandler<T>. So, you need to declare handler as a ResponseHandler<MeetingClientResponse<ScheduleMeetingResponseVO>> (or a sub type):

ResponseHandler<MeetingClientResponse<ScheduleMeetingResponseVO>> handler;

I emphasized the word declare because the declaration is what matters. If your handler is declared as a ResponseHandler<JsonResponse<ScheduleMeetingResponseVO>>, you get a compile error, even if you handler is in fact a ResponseHandler<MeetingClientResponse<ScheduleMeetingResponseVO>>.

Étienne Miret
  • 6,448
  • 5
  • 24
  • 36