5.4 Interfaces

Previous Index Next 


 Java has a special type called an Interface. An Interface is declared in the same way that a class is except that the keyword interface is used instead of class.

Interfaces are essentially classes that have no implementation. In other words an Interface only declare which methods it has, but not the code for the methods. An Interface cannot have any attributes.

The following is a definition of an interface:

public interface Shape
 {
  public void draw();
  public void moveTo(int x, int y);
 }
A Java class can implement one or more interfaces. When a class does this it must declare methods that match the methods in the interface. For instance:
public class Box extends GuiObject implements Shape
 {
  public void draw()
   {
    //... draw code goes here
   }

  public void moveTo(int x, int y)
   {
    //.. move code goes here
   }
 }
The Box class above extends the GuiObject class so it inherits all the GuiObject's methods and attributes. The Box class also implements the Shape interface which means that it must implement the draw() and moveTo() methods. Also any code that manipulates the Shape type will be able to manipulate objects of the Box class.

Interfaces allow a form of multiple inheritance in Java. The Java API uses interfaces extensively. Some examples are:



Sources