简体   繁体   中英

Polymorphism in Java

Why everybody uses Polymorphism in Java while using collections.

What is the difference between these initializations.

  private List<Order> orderList = new ArrayList<Order>();
  private ArrayList<Order> orderList = new ArrayList<Order>();

In the second form, your orderList can be treated only as an ArrayList<Order> or something inheriting from ArrayList<Order> .

In the first form, your orderList is treated as a List<Order> and this is recommended when you only use functionality defined by List<T> interface. This way the code is more flexible and can be easily refactored (eg you realize that you need a LinkedList<T> instead, you change the initialization and most of the code does not need to be changed).

Also, it is helpful for code refactoring to use interfaces instead of actual types, if possible (eg use parameters of type List<T> instead of ArrayList<T> ), because it allows the caller to change list type without changing anything in the called function.

Using the List or Collection interface don't force the orderList variable in a specific implementation. Your code will run just as always, but if you want to use a LinkedList , or a HashSet if the Collection order is not important, you'll be free to do it.

You may not find that very useful if the scope of orderList is just your method, but it helps a lot when you're using or writing a public method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM