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. Thus 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 could contain any type of object that implemented the CellAble interface (or in other words implemented the list of methods). Objects that implemented the CellAble interface would 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 |