0

Say I have an interface:

public interface IDto {
}

and a class that implements this interface:

public class UserProfileResponseDto implements IDto {
}

In another interface I have:

public interface ISortingController {
    public List<IDto> findAll();
}

In my concrete controller I have:

public List<UserProfileResponseDto> findAll();

but its telling me that it must be

public List<IDto> findAll();

Is there a way that would allow public List<UserProfileResponseDto> findAll(); as it feels like it should be allowed since UserProfileResponseDto implements IDto. The reason I ask this question is because I feel that it gives more verbosity the the controller class, which would make it easier to maintain and operate with.

yasgur99
  • 756
  • 2
  • 11
  • 32
  • 2
    Declare it as `public List extends IDto> findAll();` – Johannes Kuhn Sep 24 '19 at 22:23
  • [Covariance, Invariance and Contravariance explained in plain English?](https://stackoverflow.com/questions/8481301/covariance-invariance-and-contravariance-explained-in-plain-english) – jaco0646 Sep 25 '19 at 01:51

1 Answers1

3

You need to declare a type parameter in your ISortingController like this:

public interface ISortingController<D extends IDto> {
    public List<D> findAll();
}

and your controller implementation needs to say implements ISortingController< UserProfileResponseDto>.

Erwin Bolwidt
  • 30,799
  • 15
  • 56
  • 79