What is an Interface? How to use Java Interface ?
------------------------ A Tool class and its class hierarchy defines what a Tool can and cannot do in terms of its characteristics. However a Tool can have a different relationship with other parts of the world. For example, a Tool in a store could be managed by an inventory program. An inventory program doesn't care what class of items it manages as long as each item provides certain information, such as price and tracking number.
Instead of forcing class relationships on otherwise unrelated items, the inventory program sets up a protocol of communication. This protocol comes in the form of a set of constant and method definitions contained within an interface. The inventory interface would define, but not implement, methods that set and get the retail price, assign a tracking number, and so on.
To work in the inventory program, the Tool class must agree to this protocol by implementing the interface. When a class implements an interface, the class agrees to implement all the methods defined in the interface. Thus, the Tool class would provide the implementations for the methods that set and get retail price, assign a tracking number, 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 among 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.
An interface is a contract in the form of a collection of method and constant declarations. When a class implements an interface, it promises to implement all of the methods declared in that interface. Interfaces are useful for capturing similarities among unrelated classes without artificially forcing a class relationship, declaring methods that one or more classes are expected to implement and revealing an object's programming interface without revealing its class. Java uses
interface and
abstract class to define interfaces
See Examples:
Java Interface Example