Program to implement interfaces

Interface is the prototype of class (means we can declare the functions only)that can be implemented by any number of classes. It is the collection of methods and variables. Methods are only abstract methods means the methods has no statements. We use interface keyword to declare an interface.

 

interface dimension   //defining interface

{

/*defining abstract methods in the interface(calculate() and display())*/

void calculate(float x,float y);

void display();

}

class box implements dimension //implementing interface in the class box

{

protected float len; //defining variable len, width, area

protected float width;

protected float area;

public void calculate(float x,float y) //implementing methods

{

len=x;

width=y;

area=len*width;

}

public void display() //publicly declared

{

System.out.println();

System.out.println();

System.out.println("   "+"Length of the box="+len);

System.out.println("   "+"width of the box="+width);

System.out.println("   "+"area of the box="+area);

}

}

class pac implements dimension //implementing interface in different class pac

{

protected float len1;

protected float width1;

protected float area1;

public void calculate(float x,float y)

{

len1=x;

width1=y;

area1=len1*width1;

}

public void display()

{

System.out.println();

System.out.println();

System.out.println("   "+"Length of the Packet="+len1);

System.out.println("   "+"width of the Packet="+width1);

System.out.println("   "+"area of the Packet="+area1);

}

}

class inter

{

public static void main(String aa[])

{

box s=new box();   //s is the object of class box

pac p=new pac();   //p is the object of class pac

dimension d;   //declaring object of the interface class

d=s;

d.calculate(12,23);

d.display();

d=p;

p.calculate(32,21);

p.display();

}

}

implementing interfaces

Explanation…..

In above example an interface dimension and implements the dimension interface in the classes:box and packet. The abstract methods calculate() and display() are declared in the interface. Dimension and are implemented in the classes box and packet. The instance of each class is created using the new operator.