How to implement Interface in Java
Interface:
The interface is a kind of class, it contains methods and variables. It defines only abstract methods and final fields. It has the following syntax:
interface Interface-Name { variable declaration; methods declaration; }
Example:
interface Area { final static float pi=3.14; float calculate(float a, float b); void display(); }
Implement Interface in Java:
Interfaces are used as Superclasses whose properties are inherited by classes. It is necessary to create a class that inherits the given interface:
class class-name implements interface-name { body of class-name }
Program:
interface Area { final static float pi=3.14; float calculate(float p, float q) } class Rectangle implements Area { public float calculate(float p, float q) { return(x*y); } } class Circle implements Area { return (pi*p*p); } } class Test { public static void main(String args[]) { Rectangle rect=new Rectangle(); Circle c1=new Circle(); Area a1; //Interface object a1=rect; System.out.println("Area of Rectangle :"+a1.calculate(25, 30)); a1=c1; System.out.println("Area of Circle :"+a1.calculate(20,0); } }