next up previous
Next: Command Parsing Guidelines Up: General Notes on Java Previous: Comparators

Interfaces

One of the goals of object oriented programming is to create modular code that can easily be reused for various tasks. One good way to achieve this goal in JAVA is to use an interface.

An interface defines a set of public methods that a class must implement. The joy of using an interface is that if two different data structure implement the same interface, you should be able to switch freely between them without any problems!

Consider two classes: LinkedList and TabularList (both reside in the java.io package). The TabularList class stores values using a private tabular while the LinkedList uses dynamic memory management. Both classes, however, implement the List interface, which allows for the following:

		List list;
		TabularList tabularList = new TabularList();
		LinkedList linkedList = new LinkedList();

		list = tabularList;  // compiler casts these for us automatically
		list = linkedList; // because both implement the List interface

The real joy of interfaces is that you don't need to worry about the implementation of the class - you only need to know what the interface is. Say that you wrote a large program that has a large dictionary of information and you decide to store this information using the java.util.LinkedList class. You could pass this variable around in your program as a LinkedList, but you realize that you don't really care about the fact that you are using a *linked* list, you only care about the fact that you are using a List. So you pass the dictionary around as a List object (since LinkedList implements the List interface).

public static void main(String[] args)
{
	List masterDictionary = new LinkedList();

	// ... now 400,000 lines of code that does something fun and profitable
}

After 5 months of hard work you ship your product but your customer comes back to you and complains that the program is too slow - the O(n) access time of your LinkedList isn't fast enough! Thankfully you had the foresight to pass the LinkedList around as a List object, so you can quickly replace the LinkedList object with any other class that implements the List interface. You just happen to have a SkipList class in your code base that implements the List interface. By changing a single line of code you are able to drastically improve performance without the headaches of having to search and replace for every instance of LinkedList.

Of course, this only works if you had the foresight to use interfaces. ;)


next up previous
Next: Command Parsing Guidelines Up: General Notes on Java Previous: Comparators
MM Hugue 2004-02-28

Web Accessibility