Possible Duplicate:
Why should the interface for a Java class be prefered?
I m relatively new to java and i have just started on collections framework.
While on ArrayList
I encountered on two ways people declare it. For example to declare an ArrayList
of String
s :
List<String> l = new ArrayList<String>();
or
ArrayList<String> al = new ArrayList<String>();
Which one of these two should I use and what is the difference between them?
I know that the actual methods called are decided at runtime and hence the methods called will all be of ArrayList
class only but still the first declaration restricts the methods that can be called.
The first way is, I have heard, called "coding to an interface". Any method will be invoked using the variable l
and hence only methods provided by List
interface can be called, whereas, in the second example we can call all the methods provided not only by List
but by the Object
class also (like finalize()
, wait()
etc). So why even in the first place people even use the first declaration??