![]() ![]() ![]() |
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
In English, an interface is a device or system that unrelated entities use to interact. According to this definition, a remote control is an interface between you and a television set, the English language is an interface between two people, and the protocol of behavior enforced in the military is the interface between people of different ranks. Within the Java programming language, an interfaceis a device that unrelated objects use to interact with one another. Interfaces are probably most analogous to protocols (an agreed-upon behavior). In fact, other object-oriented languages have the functionality of interfaces, but they call their interfaces protocols.
The bicycle class and its class hierarchy defines what bicycles can and cannot do in terms of its "bicycle-ness". But bicycles interact with the world on other terms. For example, a bicycle in a store is an inventory item with a retail price, a part number, a parts list, and so on. To set or get this sort of information from a bicycle object, an inventory program and the bicycle class must agree on a protocol of communication. This protocol comes in the form of an interface, let's call it
InventoryItem
, that contains method definitions. TheInventoryItem
interface would define methods such assetRetailPrice
,getRetailPrice
, and so on.To work within the inventory program, the bicycle class must agree to this protocol by implementing the
InventoryItem
interface. When a class implements an interface, the class agrees to implement all of the methods defined in the interface. Thus, the bicycle class would have to implementsetRetailPrice
,getRetailPrice
, and so on.
You use an interface to define a protocol of behavior that can be implemented by any class anywhere in the class hierarchy. Interfaces are useful for the following:
- Capturing similarities between unrelated classes without artificially 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.)
![]() ![]() ![]() |
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |