I would like to know why we need to create an object and link it to an interface? I.e:

interface AbleToEat(){ public void eat(); } class Animal implements AbleToEat(){ @Override public void eat(){ sout("Animal is eating"); } } public class Test{ psvm{ AbleToEat ableToEat = new Animal(); ableTOEat.eat(); } } 

Why not make Animal ableToEat = new Animal() ? What is the difference, why is it done? Explain, please!

    2 answers 2

    This approach stems from the concept of abstraction, one of the key in the world of the PLO. In practice, this allows you to save the programmer who will use your code from the details of a specific implementation. Using interfaces allows you to use objects that implement the interface, regardless of what is under the hood. More specifically: there may be several objects that implement this interface, you can work with them completely equally within the framework of the implemented interface.

    For example:

     class Dog implements AbleToEat() { @Override public void eat() { sout("Dog is eating"); } } class Snake implements AbleToEat() { @Override public void eat() { sout("Mmmm rabit is tasty!"); } } class Test { ArrayList<AbleToEat> whoIsEat = new ArrayList<>(); whoIsEat.add(new Dog()); whoIsEat.add(new Snake()); for (AbleToEat something : whoIsEat) { something.eat(); } } 

    For a deeper understanding of the issue I advise you to read that abstraction in the PLO.

    • one
      An important aspect is testing. If, for example, you are testing a system in which one of the dependencies is something β€œheavy”, for example, a service that works with a large database, then in order not to run tests from a real database, you write the simulator of your service and implement it through interface. If implementation was used instead of an interface, you would have to implement a real service, which is not good. - Olexiy Morenets

    In order not to become attached to the implementation of a particular class, but to work with the indicated interface behavior. The last principle of solid is this. At any time you can substitute another implementation, but the methods will definitely remain the same!