2

Possible Duplicate:
When best to use an interface in java

Hi,

When defining a class should I always define a corresponding interface ?

What is the advantage of

List list = new ArrayList();

Why not just -

ArrayList arrayList = new ArrayList();

Thanks

Community
  • 1
  • 1
user701254
  • 3,935
  • 7
  • 42
  • 53
  • @Mark: he's not asking when to use an interface, he's asking when/why he should define a variable with the interface type or the concrete class type. – Jonah Apr 10 '11 at 21:33
  • @Jonah, in that case: http://stackoverflow.com/questions/147468/why-should-the-interface-for-a-java-class-be-prefered – Mark Elliot Apr 10 '11 at 21:42

4 Answers4

7

The advantage of doing the former allows you to switch out your implementation without having to re-declare your variable.

This way you can use ArrayList, LinkedList(anything that implements List) etc.

Mike Lewis
  • 63,433
  • 20
  • 141
  • 111
2

The advantage is that you can change the implementation for another without having to change the rest of the code. For instance, you could use a LinkedList instead.

This improves maintainability.

Edwin Dalorzo
  • 76,803
  • 25
  • 144
  • 205
0

The advantage of first way is it's shorter to type.

mdma
  • 56,943
  • 12
  • 94
  • 128
0

An interface is a contractual standard upon which other classes can be based. I like to think of it in the context of an API, or Application Programming Interface, which allows other developers to program against a standard set of methods. A class is obligated to implement the methods that the interface defines, but can also implement other private methods that may be undocumented (for example, utility methods used by the prescribed methods of the interface).

rynmrtn
  • 3,371
  • 5
  • 28
  • 44