Java 7 for Absolute Beginners

(nextflipdebug5) #1

CHAPTER 2 ■ JAVA SYNTAX


public void setInts(int[] ints);
public float getAverage();
}

Any class that uses our Average interface has to include (that is, implement) the getInts, setInts,
and getAverage methods. Also, those methods within the implementing class must have the same
arguments. So a class that includes the following method whose signature is getInts(int
numberOfIntsToGet) does not satisfy the interface's contract unless it also includes a method whose
signature is getInts(). Don't worry too much about this just now. We work through some examples as
we go, and those should clear up your understanding nicely.

Listing 2-2. The AverageImpl class

package com.apress.java7forabsolutebeginners.syntaxExample;

public class AverageImpl extends Object implements Average {
private long begin;
private long end;
private int[] ints;
private static final String EXCEPTION_MESSAGE =
"ints must contain at least one int";

public AverageImpl(int[] ints) throws IllegalArgumentException {
if (ints.length == 0){
throw new IllegalArgumentException(EXCEPTION_MESSAGE);
}
this.ints = ints;
}

@Override
public float getAverage() {
begin = System.nanoTime();
int result = 0;
for (int i = 0; i < ints.length; i++) {
result += ints[i];
}
end = System.nanoTime();
return (float) result / ints.length;
}

public static float averageTwoNumbers(int a, int b) {
return (float) (a + b) / 2;
}

// a classic getter method
@Override
public int[] getInts() {
return ints;
}

// a classic setter method
@Override
Free download pdf