Java Reference
In-Depth Information
public interface Measurer
{
double measure(Object anObject);
}
The measure method measures an object and returns its measurement. Here we use
the fact that all objects can be converted to the type Object , the È’lowest common
denominatorȓ of all classes in Java. We will discuss the Object type in greater
detail in Chapter 10 .
398
399
The improved DataSet class is constructed with a Measurer object (that is, an
object of some class that implements the Measurer interface). That object is saved
in a measurer instance field and used to carry out the measurements, like this:
public void add(Object x)
{
sum = sum + measurer.measure(x) ;
if (count == 0 || measurer.measure(maximum) <
measurer.measure(x) )
maximum = x;
count++;
}
The DataSet class simply makes a callback to the measure method whenever it
needs to measure any object.
Now you can define measurers to take on any kind of measurement. For example,
here is how you can measure rectangles by area. Define a class
public class RectangleMeasurer implements Measurer
{
public double measure(Object anObject)
{
Rectangle aRectangle = (Rectangle) anObject;
double area = aRectangle.getWidth() *
aRectangle.getHeight();
return area;
}
}
Note that the measure method must accept a parameter of type Object , even
though this particular measurer just wants to measure rectangles. The method
Search WWH ::




Custom Search