Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance Generics

Suppose I an abstract class defined like this:

public class Response<T> {
    private List<Response<T>> subResponses;
}

and two subclasses defined like this:

public class SectionResponse extends Response<SectionResponse> {
}

public class FormResponse extends Response<FormResponse> {
}

Basically all subclasses of Response need to have a list of the same class. Now somewhere else in the code I want to have a list of Response objects that can contain either subclass.

What would be the best way to define this list without using raw types? I've tried List<? extends Response<?>> but I can't call the add method on a List defined like this because the parameter is a parameterized type.

like image 985
Sarevok Avatar asked Feb 01 '26 06:02

Sarevok


1 Answers

Use the Put-Get-Rule. Namely, return List<? extends Response<?>> but accept List<? super Response<?>> as parameters. Internally you would store the the list as List<Response>

As a note, I would be wary of returning List<? extends Response<?>> on an interface since it can be invasive to the consumer. In most cases the it is better for an interface to nail down the generic type so that you are returning something like List<Response<MyType>> if at all possible.

like image 166
Andrew White Avatar answered Feb 03 '26 19:02

Andrew White