Java Reference
In-Depth Information
public int
getHours()
{
//return hr
}
// Similarly document other methods.
}
You can write the Java code of the
class
Clock
using this specification. You can also
specify the design of a class as it is shown in the programming example, Candy Machine,
later in this chapter. To become an effective and good programmer, you must avoid the
temptation to skip the design phase. It is possible that the first few programs that you
write can be coded directly. However, in general, this approach only works for very small
programs. As a matter of fact, you will spend less time implementing, debugging, and
maintaining a code that is properly designed and documented.
In this chapter, we defined the
class
Clock
. Suppose that
myClock
is a reference
variable of type
Clock
. Suppose that the object
myClock
has been created. Consider
the following statements:
myClock.setTime(5, 6, 59);
//Line 1
myClock.incrementSeconds();
//Line 2
The statement in Line 1 uses the method
setTime
to set the instance variables
hr
,
min
,
and
sec
of the object
myClock
to
5
,
6
, and
59
, respectively. The statement in Line 2 uses
the method
incrementSeconds
to increment the time of the object
myClock
by one
second. The statement in Line 2 also results in a call to the method
incrementMinutes
because, after incrementing the value of
sec
by
1
, the value of
sec
becomes
60
, which
then is reset to
0
, and the method
incrementMinutes
is invoked.
How do you think Java makes sure that the statement in Line 1 sets the instance variables
of the object
myClock
and not of another
Clock
object? How does Java make sure that
when the method
incrementSeconds
calls the method
incrementMinutes
, the
method
incrementMinutes
increments the value of the instance variable
min
of the
object
myClock
and not of another
Clock
object?
The answer is that every object has access to a reference of itself. The name of this
reference is
this
. In Java,
this
is a reserved word.
Java implicitly uses the reference
this
to refer to both the instance variables and the
methods of a class. Recall that the definition of the method
setTime
is:
Search WWH ::
Custom Search