4. Interfaces

In languages with subtyping, something interesting is possible: Suppose class A mentions only the class B. This does not mean that it can only call methods on objects created by class B. Objects created by a subclass C of B are regarded as also having the type B.

Subclassing actually conflates two distinct issues:

  1. Objects of class C are to be regarded as having types compatible with B.

  2. Code of class C can reuse code from B (inheritance).

Java provides a notion of interfaces which give more flexibility in subtyping than subclasses.

A Java interface is a pure specification part. It contains no executable code, and is used only to aid decoupling.

Here’s how it works:

  1. Instead of having a class A depend on a class B, we introduce an interface I.

  2. A now mentions I instead of B ,and B is required to meet the specification of I.

  3. Of course the Java compiler doesn't deal with behavioural specifications: it just checks that the types of the methods of B are compatible with the types declared in I.

  4. At runtime, whenever A expects an object of type I, an object of type B is acceptable.

For example: The interface List is implemented by the classes: LinkedList, ArrayList and Vector. So long as the code refers only to the interface, it will work with any of these implementation classes.

Several classes may implement the same interface,and a class may implement several interface.

In contrast,a class may only subclass at most one other class. Because of this, some people use the term ‘multiple specification inheritance’ to describe the interface feature of Java, in contrast to true multiple inheritance in which can reuse code from multiple superclasses.

Interfaces bring primarily two benefits: