Instantiating interfaces in Java

前端 未结 14 1596
南笙
南笙 2020-12-07 21:08

I have this interface:

public interface Animal {
    public void Eat(String name);
}

And this code here implements the interface:



        
14条回答
  •  北荒
    北荒 (楼主)
    2020-12-07 21:13

    What you're observing here is the Dependency inversion aspect of SOLID.

    Your code is depending on the abstraction of the Animal contract by instantiating a concrete implementation of it. You're merely stating, "I'm instantating some object, but regardless of what that object actually is, it will be bound to the contract of the Animal interface."

    Take, for instance, these sorts of declarations:

    List wordList = new LinkedList<>();
    Map mapping = new HashMap<>();
    

    In both of those cases, the primary aspect of the list and map is that they follow the generic contract for a List and Map.

提交回复
热议问题