Within the Java programming language, an interface is a type, just as a class is a type. Like a class, an interface defines methods. Unlike a class, an interface never implements methods; instead, classes that implement the interface implement the methods defined by the interface. A class can implement multiple interfaces.
The bicycle class and its class hierarchy define what a bicycle can and cannot do in terms of its "bicycleness." But bicycles interact with the world on other terms. For example, a bicycle 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 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 bicycle 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 bicycle 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
- Modelling multiple inheritance, a feature that some object-oriented languages support that allows a class to have more than one superclass
/* Area Of Rectangle and Triangle using Interface * /
interface Area
{
float compute(float x, float y);
}
class Rectangle implements Area
{
public float compute(float x, float y)
{
return(x * y);
}
}
class Triangle implements Area
{
public float compute(float x,float y)
{
return(x * y/2);
}
}
class InterfaceArea
{
public static void main(String args[])
{
Rectangle rect = new Rectangle();
Triangle tri = new Triangle();
Area area;
area = rect;
System.out.println("Area Of Rectangle = "+ area.compute(1,2));
area = tri;
System.out.println("Area Of Triangle = "+ area.compute(10,2));
}
}
/** OUTPUT **
Area Of Rectangle = 2.0
Area Of Triangle = 10.0
*/
0 comments:
Post a Comment