Objects, Classes, and Interfaces |
Definition: An interface is a collection of method definitions (without implementations) and constant values.
You use interfaces to define a protocol of behavior that can be implemented by any class anywhere in the class hierarchy. A better approach to the spreadsheet cell problem would be to create an interface, say
CellAble
, that defined the list of methods that a "cell value" must implement:toString
,draw
,toFloat
, and so on. Then the spreadsheet cells can contain any type of object that implements theCellAble
interface (or in other words, implements the list of methods). Objects that implement theCellAble
interface do not have to be hierarchically related.Interfaces are useful for:
- Capturing similarities between unrelated classes without forcing a class relationship.
- Declaring methods that one or more classes are expected to implement.
- Revealing an object's programming interface without revealing its class. (Objects such as these are called anonymous objects and can be useful when shipping a package of classes to other developers.)
In Java, an interface is a reference data type and, as such, can be used in many of the same places where a type can be used (such as in method arguments and variable declarations). You'll see how to do this in Using an Interface as a Type.
Interfaces Do Not Provide Multiple Inheritance
Often interfaces are touted as an alternative to multiple class inheritance. While interfaces may solve some of the same problems as multiple class inheritance, they are quite different animals. In particular:
- You cannot inherit variables from an interface.
- You cannot inherit method implementations from an interface.
- The interface hierarchy is independent of a the class hierarchy--classes that implement the same interface may or may not be related through the class hierarchy. This is not true for multiple inheritance.
Objects, Classes, and Interfaces |