Why do you assign an objects to an interface?

前端 未结 6 1019

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:21

    What is the difference between the above code and

    LinkedList name = new LinkedList();
    

    or

    Queue name = new LinkedList();
    

    There are a few key differences.

    The difference between using the List interface and using a LinkedList object is that I'm defining my interaction with the implementing object to adhere to the List interface. Ultimately, I don't care what the implementation is*, so long as it behaves like a List of some kind.

    If I use the concrete LinkedList object, then I not only have to care what the type is, but I can use more things than I probably should - since it implements the Queue interface too, I can do queue-like operations on it, which may or may not be appropriate.

    Ultimately, your code should be SOLID; here, we adhere to the dependency inversion principle, which allows us to depend on the interface as opposed to the concrete implementation. It allows us to subsitute the LinkedList for an ArrayList should we want to.

    *: Of course you should care what the underlying implementation is, for performance reasons. But, you may not care yet.

提交回复
热议问题