CHAPTER 2 ■ JAVA SYNTAX
public void setInts(int[] ints) throws IllegalArgumentException {
if (ints.length == 0){
throw new IllegalArgumentException(EXCEPTION_MESSAGE);
}
this.ints = ints;
}
public long getRunTime() {
return end - begin;
}
}
The AverageImpl implements the Average interface. (“Impl” is an abbreviation that is often used for
a class that implements an interface.) In particular, it implements the three methods defined by the
Average interface. As you can see, it does some other things, too, including defining a message to use
when things go wrong (an exception is Java's way of saying it found something didn't work) and giving
us the tools to keep track of how long it takes to average whatever numbers we provide as input.
Listing 2-3. The AverageTest class
package com.bryantcs.examples.syntaxExample;
import java.text.SimpleDateFormat;
import java.util.Date;
public class AverageTest {
public static void main(String[] args) {
// set up a test for AverageImpl
int[] ints = {1, 2, 3, 4};
AverageImpl averageImpl = new AverageImpl(ints);
// do one test
String testString = buildTestString(averageImpl.getInts(),
averageImpl.getAverage(), averageImpl.getRunTime());
System.out.println(testString);
// set up a second test (using setInts)
ints[0] = 2;
ints[1] = 3;
ints[2] = 4;
ints[3] = 5;
averageImpl.setInts(ints);
// do the second test
testString = buildTestString(averageImpl.getInts(),
averageImpl.getAverage(), averageImpl.getRunTime());
System.out.println(testString);
// Test the exception
int[] ints2 = {};
try {
averageImpl.setInts(ints2);