Why should the interface for a Java class be preferred?

后端 未结 10 1533
陌清茗
陌清茗 2020-11-22 05:43

PMD would report a violation for:

ArrayList list = new ArrayList();


The violation was \"Avoid using implementat

10条回答
  •  忘掉有多难
    2020-11-22 06:18

    Why should the latter with List be used instead of ArrayList?

    It's a good practice : Program to interface rather than implementation

    By replacing ArrayList with List, you can change List implementation in future as below depending on your business use case.

    List list = new  LinkedList(); 
    /* Doubly-linked list implementation of the List and Deque interfaces. 
     Implements all optional list operations, and permits all elements (including null).*/
    
    
    

    OR

    List list = new  CopyOnWriteArrayList(); 
    /* A thread-safe variant of ArrayList in which all mutative operations
     (add, set, and so on) are implemented by making a fresh copy of the underlying array.*/
    
    
    

    OR

    List list = new  Stack(); 
    
    /* The Stack class represents a last-in-first-out (LIFO) stack of objects.*/
    
    
    

    OR

    some other List specific implementation.

    List interface defines contract and specific implementation of List can be changed. In this way, interface and implementation are loosely coupled.

    Related SE question:

    What does it mean to "program to an interface"?

    提交回复
    热议问题