CS106A
Handout 19
Spring 2011
April 22
nd
, 2011
Class Design and Implementation
The majority of Chapter 6—which you should be reading over the course of the next few
days—discusses classes, objects, object orientation, interface design, and implementation.
We’ll discuss both how to design a class as well as how to implement one over the course
of today’s lecture.
Harmonic Numbers
The following program prints out the first 20 Harmonic numbers, where the n
th
Harmonic number is understood, by definition, to be the sum of the first n unit
reciprocals.
The implementation is fairly straightforward, provided we make use of an invented
class called the
Rational
, which programmatically imitates the idea of a rational
number represented as a fraction.
In the same way we invent method names as part of
the procedural decomposition process, we can invent new object types—beyond the
ones already available to us—and absolutely should do so if it helps us model a complex
piece of data.
The
Rational
class doesn’t exist in core Java or in the ACM/CS106A
libraries, so we’ll need to implement it ourselves.
We can, however, pretend the class
exists and further pretend objects of the invented class type respond to a small number
of sensible, relevant methods.
public
class
HarmonicNumbers
extends
ConsoleProgram {
public
void
run() {
println("This program prints out the first 20 Harmonic numbers.");
println();
Rational sum =
new
Rational(0);
for
(
int
d = 1; d <= 20; d++) {
Rational unitFraction =
new
Rational(1, d);
sum = sum.add(unitFraction);
println("
" + d + ".) " + sum);
}
}
}
We make use of a
Rational
constructor, an add method, and an ability to implicitly
serialize a
Rational
to string form so it can be printed.
You should also note that we
can construct a
Rational
in two ways—with one parameter, or with two.
And without
thinking about it too much, we just assume that the presentation of the rational in strong
form will print it in reduced form (yes to 2/3, no to 6/9, as an example).
When inventing new class types, it’s best to think how you’d like objects of that type to
interact with your program.