Java Reference
In-Depth Information
8
SimpleTime time = new SimpleTime( 15 , 30 , 19 );
9
System.out.println(time.buildString());
10
}
11
} // end class ThisTest
12
13
// class SimpleTime demonstrates the "this" reference
14
class SimpleTime
15
{
16
private int hour; // 0-23
17
private int minute; // 0-59
18
private int second; // 0-59
19
20
// if the constructor uses parameter names identical to
21
// instance variable names the "this" reference is
22
// required to distinguish between the names
23
public SimpleTime( int hour, int minute, int second)
24
{
25
this .hour = hour; // set "this" object's hour
this .minute = minute; // set "this" object's minute
this .second = second; // set "this" object's second
26
27
28
}
29
30
// use explicit and implicit "this" to call toUniversalString
31
public String buildString()
32
{
33
return String.format( "%24s: %s%n%24s: %s" ,
34
"this.toUniversalString()" ,
this .toUniversalString()
toUniversalString()
,
35
"toUniversalString()" ,
);
36
}
37
38
// convert to String in universal-time format (HH:MM:SS)
39
public String toUniversalString()
40
{
41
// "this" is not required here to access instance variables,
42
// because method does not have local variables with same
43
// names as instance variables
44
return String.format( "%02d:%02d:%02d" ,
45
this .hour this .minute this .second
,
,
);
46
}
47
} // end class SimpleTime
this.toUniversalString(): 15:30:19
toUniversalString(): 15:30:19
Fig. 8.4 | this used implicitly and explicitly to refer to members of an object. (Part 2 of 2.)
Class SimpleTime (lines 14-47) declares three private instance variables— hour ,
minute and second (lines 16-18). The class's constructor (lines 23-28) receives three int
arguments to initialize a SimpleTime object. Once again, we used parameter names for the
constructor (line 23) that are identical to the class's instance-variable names (lines 16-18),
so we use the this reference to refer to the instance variables in lines 25-27.
Search WWH ::




Custom Search