Interfaces

An interface is a way of grouping methods that will support a related function. A class declares that it supports a specific interface as follows:

public class MyProgram implements MyInterface { ... }

Interfaces are written using the interface keyword as follows:

public interface MyInterface {
    void myFirstMethod();
    int mySecondMethod(String param);
}

In the above example, the class MyProgram must have actual methods called myFirstMethod() and mySecondMethod() whose signatures match those defined in the MyInterface interface.

An example of an interface that we used in Level 1, is the KeyListener interface. Any class that implements the KeyListener interface, must also have the following methods, whether or not they have any code inside their curly brackets:

public void keyTyped(KeyEvent e) { }
public void keyPressed(KeyEvent e) { }
public void keyReleased(KeyEvent e) { }

A single class can implement more than one interface. For example, if a program will respond to key presses AND mouse clicks, the class can be declared as follows:

public class MyProgram implements KeyListener, MouseListener { .... }

Now the class must have all the following methods:

public void keyTyped(KeyEvent e) { }
public void keyPressed(KeyEvent e) { }
public void keyReleased(KeyEvent e) { }
public void mouseClicked(MouseEvent e) { }
public void mousePressed(MouseEvent e) { }
public void mouseReleased(MouseEvent e) { }
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }

Prior to Java 8, interfaces could only contain abstract methods (i.e. method signatures only), but later versions allow for interfaces to contain a default implementation of method function. However, if a non-abstract class implements an interface, it must have a method for every abstract method in the interface (see "Abstract" tutorial for more information about abstract elements).

Things to find out before you finish this module:

  • How to implement an interface

  • The similarities and differences between a Java abstract class and a Java interface

  • When to use an abstract class or an interface

  • Sample Program

    Student Recipes

    TextFunkifier