-2

What is the difference between

Collection c = new ArrayList();

And

ArrayList c = new ArrayList();

They seem to be both of type ArrayList and thus able to invoke the same methods.

Massi A
  • 30
  • 5
  • Has something to do with polymorphism – Dylan Czenski Jan 08 '16 at 12:47
  • 2
    Possible duplicate of [Why do we first declare subtypes as their supertype before we instantiate them?](http://stackoverflow.com/questions/8761188/why-do-we-first-declare-subtypes-as-their-supertype-before-we-instantiate-them) – Joe Jan 08 '16 at 12:49

2 Answers2

2

In the second case you can call methods on c that are specific to ArrayList as c is declared as type ArrayList.

In the first case, you can only call methods that are defined for Collection (and must also be in ArrayList).

For example, ArrayList declares functions that use indexes (such as get and indexOf) but Collection does not have them.

rghome
  • 8,529
  • 8
  • 43
  • 62
2

A Collection is an interface that defines the highest-level of shared collection behavior, and extends Iterable (which just defines the iterator() method).

A List is an interface that defines the highest-level of shared List behavior.

ArrayList is an implementation of List and in general wouldn't be used in a declaration unless you need an implementation guarantee (e.g., fast indexed access), but is fine to use as a list value.

Read the docs to see the differences–they're described in the API. The implementation (ArrayList) will have a type-specific implementation of each method in each interface it implements.

Tomaltach
  • 913
  • 1
  • 11
  • 30