Interface

Interface:

An interface is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface.

An interface is not a class. Writing an interface is similar to writing a class, but they are two different concepts. A class describes the attributes and behaviors of an object. An interface contains behaviors that a class implements.

Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class.

Defining an interface is similar to creating a new class:

public interface OperateCar {

 

// constant declarations, if any

 

// method signatures

 

// An enum with values RIGHT, LEFT

int turn(Direction direction,

double radius,

double startSpeed,

double endSpeed);

int changeLanes(Direction direction,

double startSpeed,

double endSpeed);

int signalTurn(Direction direction,

boolean signalOn);

int getRadarFront(double distanceToCar,

double speedOfCar);

int getRadarRear(double distanceToCar,

double speedOfCar);

……

// more method signatures

}

Note that the method signatures have no braces and are terminated with a semicolon.

Example:
interface SessionIDCreator extends SerializableCloneable{
String TYPE = “AUTOMATIC”;
int createSessionId();
}

class SerialSessionIDCreator implements SessionIDCreator{

private int lastSessionId;
@Override
public int createSessionId() {
return lastSessionId++;
}

}

 

In above example of interface in Java, SessionIDCreator is an interface while SerialSessionIDCreator is a implementation ointerface.

 

Multiple inheritance of interfaces:

Multiple inheritance is a feature of some object oriented computer programming languages in which a class can inherit characteristics and features from more than one superclass. It is distinct to single inheritance where a class may only inherit from one particular superclass.

Simple Program On Java for the implementation of Multiple inheritance using interfaces to calculate the area of a rectangle and triangle
/* 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

/