Java Interface

From JavaProgramming

An interface is basically the same as a class with no member variables and abstract methods only.

Java does not support multiple inheritance. In the class diagram below is an inheritance-tree where Boat and Car inherits from the abstract class Vehicle. At the same time Boat and Car should inherit from Rentable. This is not possible in Java.

[BrokenImage]

Java has a construct which is new to C++ programmers; interface. This construct will will allow a technique which have similarities to multiple ineritance.

In the class diagram below, Boat and Car implements the interface Rentable. Boat and Car must overload all abstract methods which is declared for Rentable. Interfaces are also part of the UML standard for modelling Object-Oriented systems. The notation for an interface is a circle, or alternatively a class symbol (a box) with stereotype <<interface>>.

[BrokenImage]

This test program shows an implementation of the classes from the class diagram above:

 /* TestInterface.java */
 interface Rentable {
   public void handOut();
   public void handIn();
 }

// Abstract classes need not implement supported interfaces abstract class Vehicle implements Rentable { int position; public Vehicle(int p) { position = p; } abstract public String getDescr(); }

// Concrete classes must implement all methods of the supported interfaces class Car extends Vehicle { int wheels; public Car(int p, int w) { super(p); // Call the constructor of the superclass wheels = w; } // Overload method from abstract class Vehicle public String getDescr() { return "Car with " + wheels + " wheels"; } // Implement the methods of the Rentable interface public void handOut() { System.out.println("Hand out " + getDescr()); } public void handIn() {} }

class Boat extends Vehicle implements Rentable { int masts; public Boat(int p, int m) { super(p); masts = m; } public String getDescr() { return "Boat with " + masts + " masts"; } public void handOut() { System.out.println("Hand out " + getDescr()); } public void handIn() {} }

public class TestInterface { public static void main(String[] args) { Rentable[] rentables = new Rentable[2]; rentables[0] = new Car(0, 4); rentables[1] = new Boat(0, 2); for(int i=0; i<2; i++) // Output: Hand out car vehicles[i].handOut(); // Hand out boat } }


EditText of this page (last edited July 25, 2004) or FindPage with title or text search