-1

I have observed in Java programming language, we code like following:

List mylist = new ArrayList();

Why we should not use following instead of above one?

ArrayList mylist = new ArrayList();
Akshay Lokur
  • 6,680
  • 13
  • 43
  • 62

5 Answers5

1

While the second option is viable, the first is preferable in most cases. Typically you want to code to interfaces to make your code less coupled and more cohesive. This is a type of data abstraction, where the user of mylist (I would suggest myList), does not care of the actual implementation of it, only that it is a list.

Pete B.
  • 3,188
  • 6
  • 25
  • 38
1

We may want to change the underlying data structure at some point, and by keeping references, we only need to change the declaration.

Joel
  • 5,618
  • 1
  • 20
  • 19
1

The separation of Abstract Data Type and specific implementation is one the key aspects of object oriented programming.

See Interface Instansiation

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

If you use ArrayList, you are saying it has to be an ArrayList, not any other kind of List, and to replace it you would have to change every reference to the type. If you use List you are making it clear there is nothing special about the List and it is used as a plain list. It can be changed to another List by changing just one line.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

Just to avoid tight coupling. You should in theory never tie yourself to implementation details, because they might change, opposite to interface contract, which is supposed to be stable. Also, it really simplifies testing.

You could view interface as an overall contract all implementing classes must obey. Instead, implementation-specific details may vary, like how data is represented internally, accessed, etc. - the information that you'd never want to rely on.

skuntsel
  • 11,624
  • 11
  • 44
  • 67