Why should the interface for a Java class be preferred?

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

PMD would report a violation for:

ArrayList list = new ArrayList();


The violation was \"Avoid using implementat

10条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 06:18

    In general for your line of code it does not make sense to bother with interfaces. But, if we are talking about APIs there is a really good reason. I got small class

    class Counter {
        static int sizeOf(List items) {
            return items.size();
        }
    }
    

    In this case is usage of interface required. Because I want to count size of every possible implementation including my own custom. class MyList extends AbstractList....

提交回复
热议问题