Next page | Contents page |

Interfaces (multiple inheritance)

A Java class can extend only one superclass but it can implement any number of interfaces. An interface is a declaration of behaviour, ie, public methods. Anything that implements a given interface is known to be capable of doing everything specified in the interface. Therefore an interface specifies a type, just as a class does. The name of the interface must be a capital letter (universal convention) and the interface must reside in a file of exactly the same name (plus .java) just like a class.

Declaration is similar to replacing abstract class by the keyword interface. There can be no fields, no method implementations, no constructors. Eg, for geometrical shapes:

	public interface Centred
	{
		void setCentre (double cx, double cy);
		void setCentre (Point p);
		double getCentreX ();
		double getCentreY ();
		Point getCentre ();
		double area (); // Each implementing shape knows how to calculate
		double perimeter ();
	} // Centred

Note that because these methods must be public there is no need (and it is bad style) to state that.

Implementing an interface

To use the interface Centred, we might have:

	public class Rectangle extends Shape implements Centred
	{
		private double cx, cy;  private double width, height;

		public void setCentre (double cx, double cy)
		{ this.cx = cx;  this.cy = cy;  }

		public double area ()
		{ return width * height; } 
		// NB: Different from how other shapes might do this.
	// etc... 

The compiler insists we provide implementations of all of the interface methods.

We might then have several shapes implementing Centred:

	Shape [] shapes = new Shape [n];
	shapes [0] = new Rectangle (200, 100); 
	// NB: no cast needed: a Rectangle is a Shape
	//...define other elements

	for (int i = 0; i < shapes.length; i++)
	{
		if (shapes [i] instanceof Centred)
		{
			Centred c = (Centred) shapes [i]; // NB use of interface type
			double cx = c.getCentreX ();

This also illustrates processing an array of mixed objects - OK because of common ancestry. They are all also of type Shape.

Further notes on interfaces

  1. A class can implement several interfaces:
    public class Animate implements Runnable, MouseListener, MouseMotionListener { ... }
  2. Interfaces can also be extended (ie, subclassed):
    public interface Positionable extends Centered { ... }

Subclass, abstract class or interface?

Next page | Contents page |