Java Reference
In-Depth Information
Body earth = new Body(); // idNum is 1
earth.name = "Earth";
earth.orbits = sun;
The
Body
constructor is invoked when
new
creates the object but
after
name
and
orbits
have been set to their default initial values.
The case shown herein which you know the name of the body and what
it orbits when you create itis likely to be fairly common. You can provide
another constructor that takes both the name and the orbited body as
arguments:
Body(String bodyName, Body orbitsAround) {
this();
name = bodyName;
orbits = orbitsAround;
}
As shown here, one constructor can invoke another constructor from the
same class by using the
this()
invocation as its first executable state-
ment. This is called an
explicit constructor invocation.
If the constructor
you want to invoke has arguments, they can be passed to the construct-
or invocationthe type and number of arguments used determines which
constructor gets invoked. Here we use it to invoke the constructor that
has no arguments in order to set up the
idNum
. This means that we don't
have to duplicate the
idNum
initialization code. Now the allocation code is
much simpler:
Body sun = new Body("Sol", null);
Body earth = new Body("Earth", sun);