Java Reference
In-Depth Information
Example 2•7: Averager.java (continued)
/** This method returns the average of all numbers passed to addDatum() */
public double getAverage() { return sum / n; }
/** This method returns the standard deviation of the data */
public double getStandardDeviation() {
return Math.sqrt(((sumOfSquares - sum*sum/n)/n));
}
/** This method returns the number of numbers passed to addDatum() */
public double getNum() { return n; }
/** This method returns the sum of all numbers passed to addDatum() */
public double getSum() { return sum; }
/** This method returns the sum of the squares of all numbers. */
public double getSumOfSquares() { return sumOfSquares; }
/** This method resets the Averager object to begin from scratch */
public void reset() { n = 0; sum = 0.0; sumOfSquares = 0.0; }
/**
* This nested class is a simple test program we can use to check that
* our code works okay.
**/
public static class Test {
public static void main(String args[]) {
Averager a = new Averager();
for(int i = 1; i <= 100; i++) a.addDatum(i);
System.out.println("Average: " + a.getAverage());
System.out.println("Standard Deviation: " +
a.getStandardDeviation());
System.out.println("N: " + a.getNum());
System.out.println("Sum: " + a.getSum());
System.out.println("Sum of squares: " + a.getSumOfSquares());
}
}
}
A Linked List Class
Example 2-8 displays a class, LinkedList , that implements a linked-list data struc-
ture. The example also defines a Linkable interface. If an object is to be “linked”
to a LinkedList , the class of that object must implement the Linkable interface.
Recall that an interface defines methods but doesn't provide any bodies for those
methods. A class implements an interface by providing an implementation for each
method in the interface and by using the implements keyword in its declaration.
Any instance of a class that implements Linkable can be treated as an instance of
Linkable .A LinkedList object treats all objects in its list as instances of Linkable ,
and therefore doesn't need to know anything about their true types.
Note that this example was written for Java 1.1. Java 1.2 introduces a similar, but
unrelated class: java.util.LinkedList . This new LinkedList collection class is
more useful than the class developed in Example 2-8, but Example 2-8 is a better
example of the use of interfaces.
Search WWH ::




Custom Search