An interface is just defined like a class but a keyword interface is used instead of the keyword class. It can contain either constants (final fields) or abstract method declarations or both.
All the methods in an interface are public and abstract by default and all the fields are public, static and final by default. Its syntax is .
[public] interface InterfaceName
{
// constant variable declarations
// abstract method declarations
}
The optional public access specifier specifies whether this interface can be used by other classes and packages or not. If public access specifier is omitted, only the classes within its package can use the interface. The keyword interface indicates that an interface named InterfaceName is being defined. The rules for naming the interface are the same as that of valid Java identifiers.
For example, in order to define the Shape interface, we write
interface Shape
{
double area();
double circumference();
}
The complete Example is as shown below
interface Shape
{
double area(); // area method declaration
double circumference(); // circumference method declaration
}
class Rectangle implements Shape
{
private double length,breadth; //Instance data
public Rectangle(double l, double b)
{
length = l;
breadth = b;
}
public double area() { return length*breadth;} //Implementations of
//abstract methods
public double circumference() { return 2*(length+breadth);}
}
class Circle implements Shape
{
public static final double pI = 3.142;
private double radius;
public Circle (double r) { radius = r;}
public double area() {return pI*radius ; }//Implementations of
// abstrct methods
public double circumference() {return 2*pI*radius; }
}
class UseofInterface
{
public static void main(String[] args)
{
Shape[] s =new Shape[2]; //Create an array to hold shapes
s[0] = new Rectangle(10,20);//asssign rectangle object
s[1] = new Circle(3); //assign circle object
double total_area = 0;
for(int i = 0; i<s.length; i++)
{
System.out.println("Area = " +s[i].area()); // Compute area of shapes
//Compute circumference of shape
System.out.println("Circumference = " +s[i].circumference());
}
}
}