Java Interfaces – A Simple How-To Guide

Confused about the purpose and practical use of Java interfaces? You’re not alone. In this article we provide a step-by-step, detailed guide to Java interfaces, including what purpose they serve, why they are useful, and how to write and use them. I’ll also take you through a practical, real-world example of a program that uses interfaces in Java.

Before we get into the nitty-gritty of Java interfaces, let’s explain a little about the sample program we are going to create. It’s a simple program that utilises Java Applet technology to draw and animate a bouncing ball on the screen that bounces from virtual wall to wall.

Java Applet technology allows you to extend a class with Applet which gives it the ability to be run from a Web browser and executed by the JVM (Java Virtual Machine). I’m not going to cover Applets in any great detail, suffice to say that all you really need to do is extend the class you want to run as an applet with Applet, and insert the following line into the body portion of your HTML file that you want to run the applet:

<APPLET CODE="nameofclass.class" WIDTH="300" HEIGHT="300"></APPLET>

Simply replace ‘nameofclass’.class with the class name of the compiled Java file you want to run, and set the other width and height settings appropriately.

Now, with that out of the way, let’s look at the code that will enable us to animate a bouncing ball by creating an interface that will handle the animation for us.

First a brief introduction to Interfaces in Java.

An Interface describes a set of methods that can be called on an object.

It is a set of unimplemented, abstract methods – no method bodies, only signatures – that allows a group of unrelated classes to implement this set of common methods.

If this is confusing, think broadly.

Think of a company that has a whole number of things that need to be paid each month – such as employees and bills. Now imagine the company’s computerised system does this by calling the pay() method on any object that is payable.

We have to do the same method on a different number of objects that are all different from each other – a similar analogy would be calling a move() method on a whole bunch of different robots that implement their movement methods differently.

Another analogy is an operating system and device drivers. Let’s say an operating system wants to write something to the screen. It could do this by calling a draw() method on the video card. The operating system doesn’t know HOW whatever particular video card plugged into the machine is going to perform this method. Each video card has its own device driver that implements the draw() method and carries it out in its own way.

So to understand interfaces you need to think of a system as a whole that needs to call certain methods, but doesn’t know who or what is going to perform these methods.

In the following example, we’ll think of a similar situation. We will create a kind of ‘controlling’ object, a Timer which runs in its own thread and calls animate() on an object at a specified interval. This controlling object has NO idea what kind of object it is going to call animate() on. The only thing it MUST know for sure is that the object it will call animate() on has implemented the animate() method. This is why when a class implements interfaces, you MUST implement all of the methods of that interface.

Now, with that in mind, let’s look at the controlling Timer class:

	class AnimationTimer extends Thread{
		Animation animation; 
		int delay;
		public AnimationTimer(Animation animation, int delay){
			this.animation = animation;
			this.delay = delay;
		public void start_animation(){
			if (isAlive()) super.resume();
			else start();
		public void pause_animation() { suspend(); }
		// Loops, calling animate, then pause the specified time
		public void run(){
			for (;;){
				try { Thread.sleep(delay); } catch (InterruptedException e) { ; }

You can see the class extends Thread so runs in its own thread. In its run() method, it loops indefinitely and calls animate() on an Animation object – that is, any class that implements the interface Animation that we are going to define now.

interface Animation { public void animate(); }

That’s it. Really simple. The interface has one method, animate(), so any class that implements this interface MUST provide an implementation of the animate() method (or declare itself abstract).

So, let’s write a class that implements the Animation interface, and extends Applet so we can run this program as an Applet.

public class BouncingBall extends Applet implements Animation{

	int x = 150, y = 50, r = 50; // position and radius of the circle
	int dx = 11, dy = 7; // trajectory of circle
	// A timer, call our animate() method evvery 100 milliseconds. Create a new thread
	AnimationTimer timer = new AnimationTimer(this, 100);
	public void paint(Graphics g){
		g.fillOval(x-r, y-r, r*2, r*2);
	public void animate(){
		if ((x - r + dx < 0) || (x + r + dx > bounds().width)) 
			dx = -dx;
		if ((y - r + dy < 0) || (y + r + dy > bounds().height))
			dy = -dy;
		x += dx; 
		y+= dy;
		// Ask the browser to call our paint() method to draw the circle at its 
		// new position
	public void start() { timer.start_animation(); }
	public void stop() { timer.pause_animation(); }

We first set up the position and radius of our bouncing ball, which is fairly self-explanatory.

Then we create a new AnimationTimer object and pass into the constructor the current BouncingBall object – we can do this because BouncingBall implements Animation, thus IS an Animation. Remember that the parameters for the AnimationTimer constructor were an Animation object and an int, recodesenting the delay time.

We implement the paint() method, which is a method of a Java Applet you can override to draw the Applet however you’d like using a Graphics object. We simply use the Graphics object to draw a red circle and use the fillOval() method to do so.

Next, we implement the all important animate() method. We simply test if the ball has reached the bounds of the X or Y co-ordinates on the screen, and if so, reverse the direction of the animation. Then we move the circle by incrementing the X and Y variables by the trajectory (dx and dy). Finally we call repaint() to redraw the screen. Remember that the ‘controlling’ object, the AnimationTimer, is the object actually calling animate() as it has an instance of a BouncingBall in it, and it calls animate() every 100 milliseconds, as this is the parameter we passed through to the constructor.

Note you’ll need to allow the JVM permissions to execute a Java applet on your browser.

But it should show you how easy it is to implement animations and other cool stuff in Java. As an exercise, try implementing this little application on your own computer (all the source code is here), and perhaps implement some extensions – such as a user controlled paddle that allows you to hit the ball!

You may also like...