Java Reference
In-Depth Information
Objects creating objects
The first question we have to ask ourselves is: Where do these three objects come
from? When we want to use a clock display, we might create a ClockDisplay object.
We then assume that our clock display has hours and minutes. So by simply creating a
clock display, we expect that we have implicitly created two number displays for the
hours and minutes.
As writers of the ClockDisplay class, we have to make this happen. We simply write code
in the constructor of the ClockDisplay that creates and stores two NumberDisplay objects.
Because the constructor is automatically executed when a ClockDisplay object is created, the
NumberDisplay objects will automatically be created at the same time. Here is the code of the
ClockDisplay constructor that makes this work:
Object creation.
Objects can create
other objects ,
using the new
public class ClockDisplay
private NumberDisplay hours;
private NumberDisplay minutes;
Remaining fields omitted.
public ClockDisplay()
hours = new NumberDisplay(24);
minutes = new NumberDisplay(60);
Methods omitted.
Each of the first two lines in the constructor creates a new NumberDisplay object and assigns
it to a variable. The syntax of an operation to create a new object is
new ClassName ( parameter-list)
The new operation does two things:
It creates a new object of the named class (here, NumberDisplay ).
It executes the constructor of that class.
If the constructor of the class is defined to have parameters, then the actual parameters must
be supplied in the new statement. For instance, the constructor of class NumberDisplay was
defined to expect one integer parameter:
public NumberDisplay (int rollOverLimit)
Thus, the new operation for the NumberDisplay class, which calls this constructor, must
provide one actual parameter of type int to match the defined constructor header:
new NumberDisplay (24);
Search WWH ::

Custom Search