Adult web hosting - Chapter 8 Object-Based Programming 421 Fig. 8.17 Using
Chapter 8 Object-Based Programming 421 Fig. 8.17 Using the thisreference implicitly and explicitly (part 3 of 3). Class SimpleTime(lines 8 60) defines three privateinstance variables hour, minuteand second. The constructor (lines 34 39) receives three intarguments to initialize a SimpleTimeobject. Notice that the parameter names for the constructor are the same as the instance variable names. Remember that a local variable of a method with the same name as an instance variable of a class hides the instance variable in the scope of the method. For this reason, we use the thisreference to refer explicitly to the instance variables on lines 36 38. Common Programming Error 8.11 In a method in which a method parameter has the same name as one of the class members, use this explicitly if you want to access the class member; otherwise, you will incorrectly reference the method parameter. Good Programming Practice 8.7 Avoid using method parameter names that conflict with class member names. Method buildString (lines 43 48) returns a String created with a statement that uses the this reference three ways. Line 45 explicitly invokes the class s toString method via this.toString(). Line 46 implicitly uses the this reference to perform the same task. Line 47 appends thisto the string that will be returned. Remember that the this reference is a reference to an object the current Simple- Timeobject being manipulated. As before, any reference added to a String results in a call to the toString method for the referenced object. Method buildString is invoked at line 18 to display the results of the three calls to toString. Note that the same time is displayed on all three lines of the output because all three calls to toStringare for the same object. Another use of the this reference is in enabling concatenated method calls (also called cascaded method calls or method call chaining). Figure 8.18 illustrates returning a reference to a Time4object to enable method calls of class Time4to be concatenated. Methods setTime (lines 50 57), setHour (lines 60 65), setMinute (line 68 74) and setSecond(lines 77 83) each have a return type of Time4and each has as its last statement return this; to indicate that a reference to the Time4 object being manipulated should be returned to the caller of the method. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01
Note: In case you are looking for affordable and reliable webhost to host and run your business application check Vision php5 hosting services