1

I am trying to understand what is the difference between the below 2 lines of code.

I know for a reason that one is of the reference type List and the other of the reference type ArrayList. But does it really matter or is it just 2 different ways of doing the same thing ?

Its not only with these classes/interface but with others as well. I believe it is a Polymorphism feature of an object taking different forms is that correct ?

List a1 = new ArrayList();
ArrayList a1 = new ArrayList();
dev_marshell08
  • 1,051
  • 3
  • 18
  • 40

4 Answers4

2

You don't declare objects, you declare variables (and members).

The difference in the interface you have to the object. In the first case, the interface is List, whereas in the second it's ArrayList. The underlying object is the same, but you have different access to it. In theory, ArrayList could have methods that List doesn't have (although in practice I don't think it does).

The advantage to using List is that you can change the underlying object to be a different kind of list (by changing what kind you create) without breaking your contract with any code that's using it. If you declare it as ArrayList, you have to change your contract if you want to change the underlying implementation.

Disclosure: This is an adapted form of my answer to this question. It's basically the same question, but you probably wouldn't find it when looking with the terms you were using. :-)

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

List a1 is an interface meaning that for example it can reference a LinkedList as well (doesn't restrict the implementation to ArrayList).

While ArrayList a1 can be only assigned ArrayList instances, which is a restriction you don't wish to have sometimes.

It is usually considered better approach to use interfaces (List, Map etc.) instead of concrete types especially if you expose methods to external apps, therefore you don't enforce implementation details. You just expect the variable a1 to behave as a List.

Matyas
  • 13,473
  • 3
  • 60
  • 73
0

List is an interface, ArrayList implements that interface.

List a1 = new ArrayList();

a1 will be a List variable that contains an instance of the object ArrayList, the cast of the new ArrayList to List will be done implicitly.

cosmin.danisor
  • 943
  • 1
  • 12
  • 29
0

It does have to do with inheritance/polymorphism. Think of it as similar to:

Animal dog1 = new Dog();
Dog dog2 = new Dog();

Both will let you perhaps .eat(), but only dog2 can .bark()

Brian
  • 6,391
  • 3
  • 33
  • 49