Search code examples
javatypesencapsulation

Java good practice - Declarations of interface types instead of declarations of implementation types


In "O'Reilly - Programming Android" they recommend avoiding this code:

ArrayList<String> a = new ArrayList<String>();

but to replace it with this:

List<String> a = new ArrayList<String>();

They argue it's easier to maintain code if later the type of a should be changed to say a linked list. If so, why not make it of type Collection, or even Object?

I feel that as the instantiation must be changed to change its type, surely it's better to keep it type restricted as much as possible and change the extra line if needed.

Are they correct?


Solution

  • In my personal opinion you should use the interface as high (in hierarchy) as possible and have the operations you will need.

    In some cases you need just to store objects, iterate, and get them using index. List interface is providing that. Object does not provide you with these methods.

    Using Object - you will make your code less readable and there could be cast exceptions.