Hey guys. I'm starting to study Interfaces and I am sort of getting the hang of it. However, I am studying a code I got from my book and there is a specific part that I don't understand well. I put a comment besides it to see if someone could explain it to me. It's the part in the DataSet class where the Object x is added to the sum, but it goes though an invocation of the method in the Interface. Could anyone tell me why I have to put measurer.measure(x) ??? Here is the full code:
/* * Describes any class whose objects can measure other objects. */ public interface Measurer { /** * Computes the measure of an object. * @param anObject the object to be measured. * @return the measure. */ double measure (Object anObject); }
import java.awt.Rectangle; /** * Objects of this class measure rectangles by area. * @author Jean * */ public class RectangleMeasurer implements Measurer { public double measure(Object anObject) { Rectangle aRectangle = (Rectangle) anObject; double area = aRectangle.getWidth() * aRectangle.getHeight(); return area; } }
/** * Computes the average of a ser of data values. * @author Jean * */ public class DataSet { private double sum; private Object maximum; private int count; private Measurer measurer; /** * Constructs an empty data set with a given measurer. * @param aMeasurer the measurer that is used to measure data values. */ public DataSet(Measurer aMeasurer) { sum = 0; count = 0; maximum = null; measurer = aMeasurer; } /** * Adds a data value to the data set. * @param x a data value. */ public void add(Object x) { sum = sum + measurer.measure(x); // DONT UNDERSTAND THE measure(x) PART if(count == 0 || measurer.measure(maximum) < measurer.measure(x)) { maximum = x; } count++; } /** * Gets the average of the added data. * @return the average or 0 if no data has been added. */ public double getAverage() { if(count == 0) { return 0; } else { return sum/count; } } /** * Gets the larger of the added data. * @return the maximum or 0 if no data has been added. */ public Object getMaximum() { return maximum; } }
import java.awt.Rectangle; /** * This program demonstrates the use of a Measurer. * @author Jean * */ public class DataTester { public static void main(String[] args) { Measurer m = new RectangleMeasurer(); DataSet data = new DataSet(m); data.add(new Rectangle(5,10,20,30)); data.add(new Rectangle(10,20,30,40)); data.add(new Rectangle(20,30,5,15)); System.out.println("Average area:" + data.getAverage()); System.out.println("Expected: 625"); Rectangle max = (Rectangle) data.getMaximum(); System.out.println("Maximum area rectangle: " + max); System.out.println("Expeted:" + "java.awt.Rectangle[x = 10, y = 20, width = 30, height = 40]"); } }