Interface (Java): Difference between revisions

Content deleted Content added
Line 6:
 
== Overview ==
Interfaces are used to encode similarities which the 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 <code>Human</code>s and <code>Parrot</code>s as subclasses of a <code>Whistler</code> class. Rather they would most likely be subclasses of an <code>Animal</code> class (likely with intermediate classes), but both would implement the <code>Whistler</code> interface.
 
Another use of interfaces is being able to use an [[Object (computer science)|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. The call <code>whistler.whistle()</code> will call the implemented method <code>whistle</code> of object <code>whistler</code> no matter what class it has, provided it implements <code>Whistler</code>. In a more practical example, a [[sorting algorithm]] may expect an object of type {{Javadoc:SE|java/lang|Comparable}}. Thus, without knowing the specific type, it knows that objects of that type can somehow be sorted.