List l
can refer to any object of its implementation like ArrayList
,LinkedList
etc. With the first approach :
List l=new ArrayList();
You can change the implementation later without affecting the code which references it.
List l=new LinkedList();
This is called coding to an interface , not implementation. It is in accordance to Liskov Substitution Principle. Code to an interface when you know or anticipate change and/or different implementation.
The only reason I can consider declaring it as
ArrayList ar=new ArrayList();
When I am sure that the implementation will not change in future ( but remember , change is the only constant ) and I want to use ArrayList
specific methods in my code which are not defined in the List
interface, and you don't want to use a cast like :
List list = new ArrayList();
((ArrayList) list).trimToSize();