Blogadda

Blogadda
Visit BlogAdda.com to discover Indian blogs

Saturday, April 18, 2009

Need of Interfaces

Interfaces are used to encode similarities which classes of various types share, but do not necessarily constitute a class relationship. For instance, a human and a parrot can both whistle. However, it would not make sense to represent Humans and Parrots as subclasses of a Whistler class. Rather they would most likely be subclasses of an Animal class (likely with intermediate classes), but both would implement the Whistler interface.

Another use of interfaces is being able to use an object without knowing its type of class, but rather only that it implements a certain interface. For instance, if one were annoyed by a whistling noise, one may not know whether it is a human or a parrot, because all that could be determined is that a whistler is whistling. In a more practical example, a sorting algorithm may expect an object of type Comparable. Thus, it knows that the object's type can somehow be sorted, but it is irrelevant what the type of the object is. The call whistler.whistle() will call the implemented method whistle of object whistler no matter what class it has, provided it implements Whistler.

No comments: