OO Programming in Java

Interfaces


General

Interfaces are a promise that your class will implement certain methods.

If an interface is defined by:

interface Drawable {

public int width();

public int height();

}

and your class says ..

class MyClass implements Drawable {

.....

}

This means that MyClass must have two methods with signatures identical to the ones included in the interface definition....

public int width();

public int height();


Sort Example

This example demonstrates the use of a Comparable interface which, when implemented by an object, allows a vector of these objects to be sorted by a ShellSort routine. The motivation for using an interface here is so that the ShellSort code never needs to be changed, it simply sorts Comparable objects, and you can make any object a Comparable by simply implementing its interface.

The Comparable interface consists of one method:

int compare (Comparable)

This method returns a 0 if the target Comparable is equal to the compare parameter and returns +/- 1 when the target Comparable is greater or less than the compare parameter.

If we were sorting a vector of Animal objects (remember Animals have names) the compare method implemented by Animal would look like

public int compare(Comparable c) {
return (this.name().compareTo ( ((Animal) c).name() ));
}


This would result in the vector of Animals being sorted by the Animal names. compareTo is a method of String which conveniently returns the appropriate integer based on the lexical order of the name strings.

By adding implements Comparable to the class definition, and 3 lines of code for the compare method we have the capability of sorting a vector of any object.

Sort Example Code

Timer Example

This example shows how a method in any object can be called at regular time intervals simply by implementing the Timed interface and having the Timer class in the project (or at least its .class file available in the CLASSPATH).

Let's say we have a class TimerTest that we would like to receive a message every one second (perhaps we're polling a network connection). We must do three things:

- Add implements Timed to the class definition. The Timed interface has one method:

public void tick (Timer t);


- Write the tick(Timer t) method. This is the method that will be called each second.


- Initialize and start the Timer. This is done with the following code:

Timer theTimer = (new Timer (this, 1*1000)); // 1sec
theTimer.start();


The this in the Timer constructor tells the Timer which Timed object should receive the tick messages()

Once the Timer is started the tick() method will be called each second.

Timer Example Code