Java Reference
In-Depth Information
In Java,
private
,
protected
, and
public
are reserved words.
Suppose that we want to define the
class
Clock
to represent the time of day in a
program. Further suppose that the time is represented as a set of three integers: one to
represent the hours, one to represent the minutes, and one to represent the seconds. We
also want to perform the following operations on the time:
1. Set the time.
2. Return the hours.
3. Return the minutes.
4. Return the seconds.
5. Print the time.
6. Increment the time by one hour.
7. Increment the time by one minute.
8. Increment the time by one second.
9. Compare the two times for equality.
10. Copy the time.
11. Return a copy of the time.
To implement these 11 operations, we write algorithms, which we implement as methods—
11 methods to implement 11 operations. So far, the
class
Clock
has 14 members: 3 data
members and 11 methods. Suppose that the 3 data members are
hr
,
min
,and
sec
,eachof
type
int
.
Some members of the
class
Clock
will be
private
,otherswillbe
public
.Deciding
which members to make
private
and which to make
public
depends on the nature of
each member. The general rule is that any member that needs to be accessed from outside the
class is declared
public
; any member that should not be accessed directly by the user should
be declared
private
. For example, the user should be able to set the time and print the time.
Therefore, the methods that set the time and print the time should be declared
public
.
Similarly, the method to increment the time and compare the times for equality should be
declared
public
. On the other hand, users should not control the direct manipulation of the
data members
hr
,
min
,and
sec
, so we will declare them
private
. Note that if the user has
direct access to the data members, methods such as
setTime
are not needed. (However, in
general, the user should never be provided with direct access to the variables.)
The data members for the
class
Clock
are:
8
private int
hr;
//store the hours
private int
min;
//store the minutes
private int
sec;
//store the seconds
The (non-
static
) data members—variables declared without using the modifier (reserved
word)
static
—of a
class
are called instance variables. Therefore, the variables
hr
,
min
,
and
sec
are the instance variables of the
class
Clock
.
Search WWH ::
Custom Search