wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Why do we have to declare the variables with the interface class? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Why do we have to declare the variables with the interface class?" Watch "Why do we have to declare the variables with the interface class?" New topic
Author

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

Amy N. Snow
Greenhorn

Joined: Apr 09, 2008
Posts: 20
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?
Freddy Wong
Ranch Hand

Joined: Sep 11, 2006
Posts: 959

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.


SCJP 5.0, SCWCD 1.4, SCBCD 1.3, SCDJWS 1.4
My Blog
Garrett Rowe
Ranch Hand

Joined: Jan 17, 2006
Posts: 1296
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 ]

Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why do we have to declare the variables with the interface class?
 
Similar Threads
Synchronized generic types
Clarifications on Java
Serialized Objects - Reflection Inquiry
HeadFirst Design Pattern question
linked lists