Java Reference
In-Depth Information
Figure 3.2
A two-digit number
display
03
3.5
Implementing the clock display
As discussed above, in order to build the clock display, we will first build a two-digit num-
ber display. This display needs to store two values. One is the limit to which it can count
before rolling over to zero. The other is the current value. We shall represent both of these as
integer fields in our class (Code 3.1).
Code 3.1
Class for a two-digit
number display
public class NumberDisplay
{
private int limit;
private int value;
Constructor and methods omitted.
Concept:
}
Classes define
types. A class
name can be used
as the type for a
variable. Variables
that have a class as
their type can store
objects of that
class.
We shall look at the remaining details of this class later. First, let us assume that we can build
the class NumberDisplay , and then let us think a bit more about the complete clock display.
We would build a complete clock display by having an object that has, internally, two number
displays (one for the hours and one for the minutes). Each of the number displays would be a
field in the clock display (Code 3.2). Here, we make use of a detail that we have not mentioned
before: classes define types.
Code 3.2
The ClockDisplay
class containing two
NumberDisplay fields
public class ClockDisplay
{
private NumberDisplay hours;
private NumberDisplay minutes;
Constructor and methods omitted.
}
When we discussed fields in Chapter 2, we said that the word “private” in the field declaration is
followed by a type and a name for the field. Here we use the class NumberDisplay as the type
for the fields named hours and minutes . This shows that class names can be used as types.
The type of a field specifies what kind of values can be stored in the field. If the type is a class,
the field can hold objects of that class.
 
 
Search WWH ::




Custom Search