• Post Reply Bookmark Topic Watch Topic
  • New Topic

Interface vs. Class for List and Set  RSS feed

 
James DePrisco
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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().
 
Campbell Ritchie
Marshal
Posts: 56562
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And welcome to the Ranch

You will often find that sort of coding described as "program to the interface, not the implemenation".
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!