Next: Event listeners. Up: Graphical user interfaces. Previous: Components and containers.


Interfaces

Textbook: Section 12.3, part 2

Before we continue, we need to discuss interfaces. An interface is basically just a set of methods. Any class that hopes to implement the interface must implement all of the methods in the interface's set.

Despite the name, interfaces are not specific to graphical user interfaces! They're a general Java concept, that we just happen to be introducing with graphical user interfaces.

Defining an interface

Defining an interface looks a lot like defining a class, except that we can only list instance methods, and none of the instance methods have any bodies.

For example, we might have defined the following interface in our Breakout game.

public interface MovingObject {
    public void step(DrawableFrame f);
    public void draw(Graphics g);
}
This was an interface that both the Ball and the Paddle classes implemented.

Implementing an interface

When you define a class that implements the interface, you need to say so up front with an implements clause.

public class Ball implements MovingObject { //...
public class Paddle extends Block implements MovingObject { //...
Any class that has such an implements clause has to define all of the methods defined in the interface. Otherwise, there's a compiler error.

(An astute observer will notice that in Breakout, Part III, we redefined Ball's step method to return a boolean. That class didn't really implement the MovingObject interface we explained, and the compiler would refuse to let us get away with it.)

Interface variables

What makes interfaces useful is that they are types, too. The following would be completely legitimate.

DrawableFrame frame = new BreakoutFrame();
MovingObject mover = new Ball();
mover.step(frame);
mover.draw(frame.getGraphics());
Naturally, you can never create an instance of an interface.

So, interfaces in a certain sense allow you to have a class have two ``superclasses.'' Only one of these is a true Java class, but the behavior as far as converting between types makes both the implemented interface and the real parent class behave like superclasses.


Next: Event listeners. Up: Graphical user interfaces. Previous: Components and containers.