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

后端 未结 8 1497
情书的邮戳
情书的邮戳 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:46

    By declaring and using myList as a Collection, you are hiding the implementation choice you are making (in this case, that it is represented as an ArrayList). In general, this means that any things that depend on your piece of code will only rely on myList behaving as a Collection, not as an ArrayList in particular. That way if you decide to represent it as something else later on (a Set? A Linked List?) for whatever reason, you don't break anything else.

提交回复
热议问题