Computing Statistics

So far, the classes we’ve defined have modeled mathematical abstractions like rectangles and complex numbers. It is easy to imagine other objects that model things like a mailing address or a record in a database. This is not a requirement, however: classes do not have to model “things.” They merely have to hold some state (i.e., define some fields) and optionally define methods to manipulate that state. Example 2-6 is just this kind of class: it computes simple statistics about a series of numbers. As numbers are passed to the addDatum( ) method, the Averager class updates its internal state so that its other methods can easily return the average and standard deviation of the numbers that have been passed to it so far. Although this Averager class does not model any “thing,” we’ve followed the Java naming convention of giving classes names that are nouns (although, in this case, we had to use a noun that does not appear in any dictionary).

Example 2-6. Averager.java

package je3.classes; /** * A class to compute the running average of numbers passed to it **/ public class Averager { // Private fields to hold the current state. private int n = 0; private double sum = 0.0, sumOfSquares = 0.0; /** * This method adds a new datum into the average. **/ public void addDatum(double x) { n++; sum += x; sumOfSquares += x * x; } /** This method returns the average of all numbers passed to addDatum( ) */ public double getAverage( ) { return sum / n; } /** This method returns ...

Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.