I studied polymorphism and understand that it can do dynamic method binding like below.
Assuming that class Animal is abstract class.
public class AnimalReference
{
public static void main(String args[])
Animal ref // set up var for an Animal
Cow aCow = new Cow("Bossy"); // makes specific objects
Dog aDog = new Dog("Rover");
// now reference each as an Animal
ref = aCow; ref.speak();
ref = aDog; ref.speak();
}
I used to create instance of ArrayList like:
ArrayList myList = new ArrayList();
But usually I figured that people write:
Collection myList = new ArrayList();
So my confusion is what is the benefit of declaring as Collection? Also I didn’t know you can have “Collection” (which is an interface not abstract class) in front of “myList”.
Why it is not good practice to just say:
ArrayList myList = new ArrayList();
I read Collection interface and ArrayList Java documents as well as online tutorials but still not really clear..
Could anyone give me some explanation?
If you declare
myListasArrayList, you fix its concrete type. Everyone using it will depend on this concrete type, and it is easy to (even inadvertently) call methods which are specific toArrayList. If sometime later you decide to change it to e.g.LinkedListorCopyOnWriteArrayList, you need to recompile – and possibly even change – client code. Programming for interfaces eliminates this risk.Note that between
CollectionandArrayList, there is another level of abstraction: theListinterface. Typically the usage pattern of a list is very different from that of a map, set or queue. So the type of collection you need for a job is usually decided early on, and is not going to change. Declaring your variable as aListmakes this decision clear, and gives its clients useful information regarding the contract this collection obeys.CollectionOTOH is usually not very useful for more than iterating through its elements.