Java Reference
In-Depth Information
A constructor declaration consists of the class name followed by a (pos-
sibly empty) list of parameters within parentheses and a body of state-
ments enclosed in curly braces. Constructors can have any of the same
access modifiers as class members, but constructors are
not
members
of a classa distinction you can usually ignore, except when it comes to
inheritance. Constructors can also have annotations applied to them;
see
Chapter 15
.
The constructor for
Body
takes no arguments, but it performs an import-
ant functionassigning a proper
idNum
to the newly created object. In the
original code, a simple programmer errorforgetting to assign the
idNum
or not incrementing
nextID
after usecould result in different
Body
objects
with the same
idNum
. That would create bugs in code that relies on the
part of the contract that says "All
idNum
values are different."
By moving responsibility for
idNum
generation inside the
Body
class, we
have prevented errors of this kind. The
Body
constructor is now the only
entity that assigns
idNum
and is therefore the only entity that needs ac-
cess to
nextID
. We can and should make
nextID
private so that only the
Body
class can access it. By doing so, we remove a source of error for
programmers using the
Body
class.
We also are now free to change the way
idNum
values are assigned to
Body
objects. A future implementation of this class might, for example,
look up the name in a database of known astronomical entities and as-
sign a new
idNum
only if an
idNum
had not previously been assigned. This
change would not affect any existing code, because existing code is not
involved at all in the mechanism for
idNum
allocation.
The initializers for
name
and
orbits
set them to reasonable values. There-
fore, when the constructor returns from the following invocations, all
data fields in the new
Body
object have been set to some reasonable ini-
tial state. You can then set state in the object to the values you want:
Body sun = new Body(); // idNum is 0
sun.name = "Sol";