next up previous contents
Next: Interfaces: Applications Up: Abstract classes Previous: Generic functions   Contents

Multiple inheritance and interfaces

What if we want to make a class such as Circle (defined earlier) extend Comparable? Circle already extends Shape and Java does not permit multiple inheritance.

Notice, however, that Comparable is a special kind of abstract class, one that has no concrete components. In Java, this kind of abstract class can be renamed an interface--the word interface is derived from its English meaning and refers to the ``visible boundary'' of a class that implements all the methods specified in the interface.

We can redefine Comparable as follows:

  interface Comparable{
    public abstract int cmp(Comparable s);
      // return -1 if this < s, 0 if this == 0, +1 if this > s
  }

A class that extends an interface is said to ``implement'' it:

  class Myclass implements Comparable{
    ...
    public int cmp(Comparable s) { ... }
    ...
  }

In Java, a class may extend only one other class, but may implement any number of interfaces. Thus, one can have

  class Circle extends Shape implements Comparable{
     ...
    public double perimeter(){...}
     ...
    public int cmp(Comparable s){...}
     ...
  }

As we mentioned earlier, extending multiple classes might create a conflict between concrete definitions in the multiple parent classes. However, since interfaces have no concrete components, no such contradiction can occur if a class implements multiple interfaces. At most, a class may implement two interfaces that both define abstract methods with the same signature. Since the signature does not indicate anything about the ``meaning'' of the method, any implementation of the method with that signature will be automatically consistent with both its abstract definitions.


next up previous contents
Next: Interfaces: Applications Up: Abstract classes Previous: Generic functions   Contents
Madhavan Mukund 2004-04-29