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

后端 未结 8 1504
情书的邮戳
情书的邮戳 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 20:02

    If you're declaring an ArrayList, I wouldn't ever use ArrayList as the type on the left side. Instead, program to the interface, be it List or Collection.

    Note that if you declare a method as taking a Collection, it can be passed a List or Set.

    As a side note, consider using Generics.

    Edit: Having said that, Generics also introduces some Gotchas.

    List could store an ArrayList, but not an ArrayList. You'd need List to store an ArrayList.

提交回复
热议问题