What is the benefit of polymorphism using Collection interface to create ArrayList object?

后端 未结 8 1502
情书的邮戳
情书的邮戳 2020-11-27 19:37

I studied polymorphism and understand that it can do dynamic method binding like below.

Assuming that class Animal is abstract class.

public class An         


        
8条回答
  •  眼角桃花
    2020-11-27 19:44

    If you declare myList as ArrayList, you fix its concrete type. Everyone using it will depend on this concrete type, and it is easy to (even inadvertently) call methods which are specific to ArrayList. If sometime later you decide to change it to e.g. LinkedList or CopyOnWriteArrayList, you need to recompile - and possibly even change - client code. Programming for interfaces eliminates this risk.

    Note that between Collection and ArrayList, there is another level of abstraction: the List interface. Typically the usage pattern of a list is very different from that of a map, set or queue. So the type of collection you need for a job is usually decided early on, and is not going to change. Declaring your variable as a List makes this decision clear, and gives its clients useful information regarding the contract this collection obeys. Collection OTOH is usually not very useful for more than iterating through its elements.

提交回复
热议问题