Why do you assign an objects to an interface?

前端 未结 6 1052

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

    If you code to interfaces you can easily switch implementations easily. If an ArrayList suits your needs better than a LinkedList then you can change one line only. If you need a particular method that is in the LinkedList class (or any other of the sub types) then it is perfectly valid to have

    LinkedList name = new LinkedList()
    

    As for the redundancy if you are referring to the generic type declaration then I would recommend you look at the Guava libraries. These have some nice static import methods to remove this. For example for an ArrayList it would be

    List name = newArrayList()
    

    instead of

    List name = new ArrayList()
    

    There is a similar method for LinkedList too.

    In Java 7 there is also the diamond operators but this is still a bit more verbose than the static import from Guava.

提交回复
热议问题