You seem to be somewhat confused as to what an interface
is, or at least how you use them. interface
in Java defines a set of method signatures that any class which implements
the interface must provide (or else be abstract
). ArrayList
is one such class which implements the List
interface. When you do the following:
List<Integer> nums = ArrayList<Integer> ()
You are creating an instance of ArrayList
, which implements all the methods of List
, and assigning it to a variable which can hold any object that implements List
. This means that when using nums
, you can only access methods exposed by List
. However, the methods actually being called are those of ArrayList
.
Java encourages using interfaces
because they aren't bound to a particular inheritance chain. Consider the following method signatures:
public <T> void foo(List<T> input)
public <T> void bar(ArrayList<T> input)
The foo
method can take anything that implements List
; this could be one of the standard library objects, like ArrayList
or LinkedList
, or it could be a user-defined class that provides completely different functionality in addition to the standard List
operations. This makes it much more flexible; foo
is simply stating that expects an object that looks and acts like a List
, but doesn't care what that object is.
The bar
method, on the other hand, uses ArrayList
directly. If later on you realize you want to use a different collection, you're stuck, because you can only use an ArrayList
or a class which extends ArrayList
.