Polymorphism via Interfaces1.6.1 Interfaces1.6.1 Interfaces1.6.2 Stacks Polymorphism via Interfaces

An interface name may be used to declare the type of a variable; the value of the variable may be (a reference) to an object of any class that implements this interface. We may use the interface methods of the object without any more knowing the actual type of the object.

Example  Using the interface and class declarations of the previous section, we may create and use a container object as follows:
  Container c = new Array();

However, it is not possible to execute

  c.setElement(0, 1);

because c is of type Container which does not contain a method setElement. For the same reason, it is not possible to refer to the object field c.l.

A variable which has an interface type is called  polymorphic ("of many forms"), because it may hold values of different types. This allows to write methods which operate in the same way on objects of different types.

Example  Take the method
  int getFirst(Container c)
    return c.getElement(0);

This method may take any Container object and return its first element. Therefore, we may write

  Container a = new Array();
  int i = getFirst(a);

Now assume we have a class declaration

  class List implements Container

Then also the following code is legal

  Container l = new List();
  int i = getFirst(l);

If a class is a special implementation of a more general concept, it is a good idea to define the general concept by a Java interface and let the class implement this interface. When we use the object, we should then refer to the interface type and not to the object type. If we later decide to use another implementation of the concept, we may do this without changing the code that uses this concept.

Example  Take the code
  Container c = new Array();
  int i = getFirst(c);

We may replace the implementation of c by changing the first line to

  Container c = new List();

The rest of the code remains unchanged.

© Wolfgang Schreiner; February 3, 2005 Polymorphism via Interfaces1.6.1 Interfaces1.6.1 Interfaces1.6.2 Stacks