When/why to use/define an interface [duplicate]
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
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.
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.
The advantage of first way is it's shorter to type.
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).
精彩评论