OO Programming in Java
Interfaces
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.
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. TheTimed
interface has one method:
public void tick (Timer t);
- Write thetick(Timer t)
method. This is the method that will be called each second.
- Initialize and start theTimer
. This is done with the following code:
Timer theTimer = (new Timer (this, 1*1000)); // 1sec
theTimer.start();
The
this
in theTimer
constructor tells theTimer
whichTimed
object should receive thetick
messages()
Once the Timer is started the tick() method will be called each second.