1

I need a little bit of help on how to work correctly with java interfaces.

I have an ArrayList with the implementation of a certain interface.

private ArrayList<ServiceClassImpl> services;

The manager class also implements an interface in which is a method who should return an ArrayList with the interface of the ServiceClass Impl

@Override
public List<IService> getAllServices() {
    return this.services;
}

Problem is that this does not work and I dont know why. With a single object it does work.

private ServiceClassImpl service;


public IService getService() {
       return this.service;
}

I don't understand it. Thanks for your help :)

JAPGamer
  • 11
  • 1
  • If you change the method return type to `List extends IService>` it should work, assuming such a change is compatible with how other code consumes this API. The other option is to make `services` a `List` instead. But for more information on why your code doesn't work, see the duplicate. – Slaw Aug 24 '22 at 20:46
  • A `List` is something you'd be able to add a `FancyServiceImpl` to, if `FancyServiceImpl` implements `IService`. But you can't do that with an `ArrayList`. Therefore, an `ArrayList` is not a `List`, so you can't return `this.services` from a method whose return type is `List`. – Dawood ibn Kareem Aug 24 '22 at 22:06

0 Answers0