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

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

    First of all there is a significant difference between inheritance and interfaces. A short trip back history: In plain old c++ you where able to inherit from multiple classes. This had a negative consequence if a "Transformer" class inherits from "Vehicle" and "Human" both of them implementing a method called "MoveForward". Which function dshoud the instance use if you call this method on the "Transformer" class? the "Human" or the "Vehicle" implementation? To solve this problem interfaces are introduced by java, c#, ... . Interfaces are a contract between you class and something else. You make a commitment to functionality but the contract does NOT implement any logic for your class (to prevent the Transformer.MoveForward" problem).

    Polymorphism in general means that something can appear in different ways. A "Transformer" can be a "Vehicle" and a "Human". Depending on you language (i use C#) you can implement different behaviours for "MoveForward", depending on the contract you want to fulfil.

    Using interfaces instead of a concrete implementation hat several advantages. First you can switch the implementation without changing the code (Dependency Injection for google lookup ;). Second you can easier test you code with testing frameworks and mocking frameworks. Third it is a good practice to use the most generalized interface data exchange (enumerator instad of a list if you only want to interate over the values).

    hope this helps a bit understanding the advantages of interfaces.

    0 讨论(0)
  • 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<Animal> could store an ArrayList<Animal>, but not an ArrayList<Cat>. You'd need List<? extends Animal> to store an ArrayList<Cat>.

    0 讨论(0)
提交回复
热议问题