| Author |
Interface vs. Class for List and Set
|
James DePrisco
Greenhorn
Joined: Nov 10, 2010
Posts: 1
|
|
I have been using the following type code without thinking about it:
List<SubNode> sub = new ArrayList<SubNode>();
However, List is an interface, not a Class. I always thought an interface was a prepackaged group of functions you add in with "implements".
The above seems to say assign a new instance of ArrayList class to interface sub. Why wouldn't I do this instead:
ArrayList<SubNode> sub = new ArrayList<SubNode>(); ?
Thanks.
|
 |
Christophe Verré
Sheriff
Joined: Nov 24, 2005
Posts: 14670
|
|
ArrayList implements List (check the class signature), or you could say that ArrayList IS-A List. So you can cast it to a List. A more explicit example of this use would look like this :
Here, you don't know (and you don't need to know) which concrete class you are using. The concrete class would be instanciated in getSubNodes():
The interesting point here is that you even if you'd change ArrayList to some other kind of List, and it would not impact on the code calling getSubNodes().
|
[My Blog]
All roads lead to JavaRanch
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32620
|
|
And welcome to the Ranch
You will often find that sort of coding described as "program to the interface, not the implemenation".
|
 |
 |
|
|
subject: Interface vs. Class for List and Set
|
|
|