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

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

    It's probably more common to write List myList = new ArrayList(); than to use Collection. Usually some aspects of it being a list are significant. The vagueness of Collection with regard to accepting duplicate elements whether it's a set or list (or whatever) underneath can be a pain.

    That aside, the primary purpose is abstraction, or implementation independence. Do I actually care if the List I have is an ArrayList or a Vector? Probably not most of the time. My code is more flexible if it uses the most general interface that expresses what I need the object to do.

    The easy example is, suppose you write a program using all ArrayLists, and then later it needs to support multiple users, so for thread safety you want to change all your ArrayLists to Vectors. If you've been passing around references to the Type ArrayList, you have to change every usage everywhere. If you've been passing around references to the Type List, you only have to change the places where you create them.

    Also, sometimes the implementing class might not be something you can or want to import and use. For example when using a persistence provider like hibernate, the actual class that implements the Set interface could be a highly specialized custom implementation unique to the framework, or it could be plain old HashSet, depending on how the object got created. You don't care about the difference, it's just a Set to you.

提交回复
热议问题