«^»
7.3. Providing your own interfaces

So far, the examples have involved interfaces that others have provided. So, when might we want to provide our own interface declarations?

We may want to do this if we have many classes that provide the same set of operations and we want to execute code that processes various objects of these different classes.

Suppose we are processing geometrical figures, some of which are circles and others are rectangles. Suppose we want to find out the area or the perimeter of these figures. We could provide the interface:

public interface Figure
{
   public double area();
   public double perimeter();
}

and provide classes called Circle and Rectangle. Here is some code for Circle:

public class Circle implements Figure
{
   private double iRadius;
   public Circle(final double pRadius)
   {
      iRadius = pRadius;
   }
   public double area()
   {
      return Math.PI*iRadius*iRadius;
   }
   public double perimeter()
   {
      return 2.0*Math.PI*iRadius;
   }
   ...
}

The code for Rectangle is similar.

Suppose we store several objects of these two classes in a list:

final List tList = new ArrayList();
tList.add( new Circle(100.0) );
tList.add( new Rectangle(200.0, 300.0) );
...

We can then process the elements of the list using code like:

final Iterator tIterator = tList.iterator(); 
while ( tIterator.hasNext() )
{
   final Figure tFigure = (Figure)tIterator.next();
   System.out.println( tFigure.area() );
}

By coding the classes as implementations of an interface we can perform operations on objects that are of different classes.