Search code examples
javainheritanceinterfaceabstraction

Function argument: abstract class or interface?


Suppose to have this class diagram, in Java:

<Interface>   <AbstractClass>      <ConcreteClass>      

                                   Γ SomethingImpl1
ISomething <- AbstractSomething <--|
                                   L SomethingImpl2

What I would like to know is what type should a function argument taking Something have.

Take ICity (and so on...) and ILocation. If ILocation has a function to set a City, e.g.:

void setCity(X city);

What should X be? ICity or AbstractCity? What is the correct signature?


Solution

  • ISomething/ICity is the correct type for the parameter provided the method only needs the features provided by the interface (which should normally be the case). In general:

    1. Code to the minimum interface you can, and

    2. In Java, make that an interface where possible (as you have done); that way, if there were a good reason to implement it not via AbstractSomething/AbstractCity, you could, and still use it with the method.