• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Why do we have to declare the variables with the interface class?

 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I've read that if you want to declare a variable that for example will contain a LinkedList, you have to declare it with the List class i.e.:


Or another example:


Why this is the best way to do it?
 
Ranch Hand
Posts: 959
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It's a good OO practice to do so. Suppose that you change your collection from LinkedList to ArrayList. To the caller, it doesn't need to know how the collection is being implemented. What it knows is that both LinkedList and ArrayList implement List.
 
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
First off, you don't have to declare your reference variables that way. It's perfectly legal to declare:

LinkedList myList = new LinkedList();

You can also declare:

Collection myCollection = new LinkedList();

It is considered by many to be a best practice to declare your reference variables with the most abstract type you can get away with, this ensures that you can only use those methods that are available to the reference type you declare it as. That way if you want to swap an implementation to a different kind of List in the future, you only have to change the declaration and nothing else.

In my opinion, this type of coding is less important at the site of instantiation, than as a return type or parameter to a method or constructor.



This type of signature is clearly preferable to returning a specific type of List (like a LinkedList) because now the clients to this method never should know or care about the concrete return type of the method. Now if you want to swap the type of list you return with an ArrayList, or a NewFangledBellsAndWhistlesList, you aren't breaking any client code.
[ August 21, 2008: Message edited by: Garrett Rowe ]
 
reply
    Bookmark Topic Watch Topic
  • New Topic