Why do you assign an objects to an interface?

前端 未结 6 1016

I have heard several times that when instantiating objects you should do:

\"Interface\" name = new \"Class\"();

For example for the class linkedlist that imp

6条回答
  •  别那么骄傲
    2020-12-31 14:24

    Firstly, an Interface is a abstract type that is used to specify what a classes must implement. Any class the implements an interface must satisfy its contract by implementing its method and is of that type.Therefore, by implementing the List interface LinkList is a type of list.

    By coding to the interface and not to the concrete class your code becomes more loosely coupled. This means that your code is not bound to the LinkList but rather the List interface and can be changed to anything that implements the list interface at anytime. Therefore, if for some reason the LinkList no longer meets you requirements and you need, lets say a ArrayList instead since it also implements the List interface you can just change to :

    List name = new ArrayList();
    

    And all your other programming logic would remain the same,since both classes have the same methods because they implement the same interface.

提交回复
热议问题