Java Reference
In-Depth Information
This is the same as for methods discussed in Section 2.4. With this constructor, we have achieved
what we wanted: if someone now creates a ClockDisplay object, the ClockDisplay con-
structor will automatically execute and create two NumberDisplay objects. Then the clock
display is ready to go.
Exercise 3.23 Create a ClockDisplay object by selecting the following constructor:
new ClockDisplay()
Call its getTime method to find out the initial time the clock has been set to. Can you work
out why it starts at that particular time?
Exercise 3.24 How many times would you need to call the timeTick method on a newly
created ClockDisplay object to make its time reach 01:00? How else could you make it
display that time?
Exercise 3.25 Create a NumberDisplay object with limit 80 in the Code Pad by typing
NumberDisplay nd = new NumberDisplay(80);
Then call its getValue() , setValue(int value) , and increment() methods in the
Code Pad (e.g., by typing nd.getValue() ). Note that statements (mutators) need a semico-
lon at the end, while expressions (accessors) do not.
Exercise 3.26 Write the signature of a constructor that matches the following object crea-
tion instruction:
new Editor("readme.txt", -1)
Exercise 3.27 Write Java statements that define a variable named window of type
Rectangle , and then create a rectangle object and assign it to that variable. The rectangle
constructor has two int parameters.
Multiple constructors
You might have noticed when you created a ClockDisplay object that the pop-up menu of-
fered you two ways to do that:
new ClockDisplay()
new ClockDisplay(int hour, int minute)
Overloading. A
class may contain
more than one con-
structor, or more
than one method of
the same name, as
long as each has
a distinctive set of
parameter types.
This is because the ClockDisplay class contains two constructors. What they provide are
alternative ways of initializing a ClockDisplay object. If the constructor with no parameters
is used, then the starting time displayed on the clock will be 00:00. If, on the other hand, you
want to have a different starting time, you can set that up by using the second constructor. It
is common for class definitions to contain alternative versions of constructors or methods that
provide various ways of achieving a particular task via their distinctive sets of parameters. This
is known as overloading a constructor or method.
Search WWH ::

Custom Search