Objects, Classes, and Interfaces |
Sometimes, you'd like classes from different parts of the class hierarchy to behave in similar ways. For example, suppose you are writing a spreadsheet program which contains a tabular set of cells, each containing one value. You'd like to be able to putString
s,Float
s,Date
s,Integer
s,Equation
s, and so on into a cell in the spreadsheet. To do so,String
s,Float
s,Date
s,Integer
s, andEquation
s would all have to implement the same set of methods. One way to achieve this is to find the common ancestor of the classes and implement the methods you need there. However, this is not a practical solution, asObject
is often the common ancestor. Except throughObject
, the objects you'd like to put in your spreadsheet cells are unrelated in the class hierarchy. But you are not allowed to modifyObject
.One approach you could take to writing the spreadsheet would be to create a class called
CellValue
that represented a value that could be contained in one of the spreadsheet's cells. Then you could create aString
,Float
,Date
,Integer
, andEquation
subclass ofCellValue
. In addition to being a lot of work, this approach arbitrarily forces a relationship on those classes that is otherwise unnecessary, and you must duplicate and re-implement classes that already exist.Java provides a better way--through interfaces.
What Are Interfaces?
An interface is a collection of method definitions (without implementations) and constant values.Defining an Interface
Defining an interface is similar to creating a new class. An interface definition has two components: the interface declaration and the interface body.The interfaceDeclaration declares various attributes about the interface such as its name and whether it extends another interface. The interfaceBody contains the constant and method declarations within the interface.interfaceDeclaration { interfaceBody }Implementing an Interface
To use an interface, you write a class that implements the interface. When a class claims to implement an interface, the class is claiming that it provides a method implementation for all of the methods declared within the interface (and its superinterfaces).Using an Interface as a Type
When you define a new interface you are in essence defining a new reference data type. You can use interface names anywhere you'd use any other type name: variable declarations, method parameters and so on.
Objects, Classes, and Interfaces |