Java Reference
In-Depth Information
Randomizer.class and Randomizer$Test.class . Running this nested Random-
izer.Test class is a little tricky. You ought to be able to do so like this:
% java com.davidflanagan.examples.classes.Randomizer.Test
However, current versions of the Java SDK don't correctly map from the class
name Randomizer.Test to the class file Randomizer$Test.class . So, to run the test
program, you must invoke the Java interpreter using a $ character instead of a .
character in the class name:
% java com.davidflanagan.examples.classes.Randomizer$Test
On a Unix system, however, you should be aware that the $ character has special
significance and must be escaped. Therefore, on such a system, you have to type:
% java com.davidflanagan.examples.classes.Randomizer\$Test
or:
% java 'com.davidflanagan.examples.classes.Randomizer$Test'
You need to use this technique whenever you need to run a Java program that is
defined as an inner class.
Computing Statistics
Example 2-7 shows a class that computes some simple statistics for a set of num-
bers. 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. Like
Randomizer , the Averager class doesn't represent any kind of real-world object or
abstract concept. Nevertheless, Averager does maintains some state (this time as
private fields), and it has methods that operate on that state, so it is implemented
as a class.
Like Example 2-6, Example 2-7 defines an inner Test class that contains a main()
method that implements a test program for Averager .
Example 2•7: Averager.java
package com.davidflanagan.examples.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;
}
Search WWH ::




Custom Search