Java Reference
In-Depth Information
public void
setTime(
int
hours,
int
minutes,
int
seconds)
{
if
(0 <= hours && hours < 24)
hr = hours;
else
hr = 0;
if
(0 <= minutes && minutes < 60)
min = minutes;
else
min = 0;
if
(0 <= seconds && seconds < 60)
sec = seconds;
else
sec = 0;
}
In the method
setTime
, the statement:
hr = hours;
is, in fact, equivalent to the statement:
this
.hr = hours;
8
In this statement, the reference
this
is used explicitly. You can explicitly use the
reference
this
and write the equivalent definition of the method
setTime
as follows:
public void
setTime(
int
hr,
int
min,
int
sec)
{
if
(0 <= hr && hr < 24)
this
.hr = hr;
else
this
.hr = 0;
if
(0 <= min && min < 60)
this
.min = min;
else
this
.min = 0;
if
(0 <= sec && sec < 60)
this
.sec = sec;
else
this
.sec = 0;
}
Notice that in the preceding definition of the method
setTime
, the name of the formal
parameters and the name of the instance variables are the same. In this definition of the
method
setTime
, the expression
this
.hr
means the instance variable
hr
, not the formal
parameter
hr
, and so on. Because the code explicitly uses the reference
this
, the
compiler can distinguish between the instance variables and the formal parameters. Of
Search WWH ::
Custom Search