aspose file tools
The moose likes Beginning Java and the fly likes Interface vs. Class for List and Set Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "Interface vs. Class for List and Set" Watch "Interface vs. Class for List and Set" New topic
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
    
  11

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
    
    4
And welcome to the Ranch

You will often find that sort of coding described as "program to the interface, not the implemenation".
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Interface vs. Class for List and Set
 
Similar Threads
is it all about performance (Arraylist) ?
can we add primitive variables in ArrayList or just objects?
Trees with arbitrary node pointers
Why use List intefrace to create a ArrayList and not ArrayList class?
sublist of arraylist???