424 Object-Based Programming Chapter 8 (Best web hosting) 105 // convert

424 Object-Based Programming Chapter 8 105 // convert to String in standard-time format 106 public String toString() 107 { 108 DecimalFormat twoDigits = new DecimalFormat( “00″ ); 109 110 return ( this.getHour() == 12 || this.getHour() == 0 ? 111 12 : this.getHour() % 12 ) + “:” + 112 twoDigits.format( this.getMinute() ) + “:” + 113 twoDigits.format( this.getSecond() ) + 114 ( this.getHour() < 12 ? " AM" : " PM" ); 115 } 116 117 } // end class Time4 Fig. 8.18 Class Time4using thisto enable chained method calls (part 3 of 3). The example again demonstrates the explicit use of the thisreference inside the body of a class. In class Time4, every use of an instance variable of the class and every call to another method in class Time4uses the thisreference explicitly. Most programmers prefer not to use the thisreference unless it is required or helps clarify a piece of code. Good Programming Practice 8.8 Explicitly using this can increase program clarity in some contexts in which this is optional. In application class TimeTest6 (Fig. 8.19), line 18 and line 26 both demonstrate method call chaining. Why does the technique of returning the this reference work? Let us discuss line 18. The dot operator (.) associates from left to right, so the expression time.setHour( 18 ).setMinute( 30 ).setSecond( 22 ); first evaluates time.setHour(18), then returns a reference to object timeas the result of this method call. Any time you have a reference in a program (even as the result of a method call), the reference can be followed by a dot operator and a call to one of the methods of the reference type. Thus, the remaining expression is interpreted as time.setMinute( 30 ).setSecond( 22 ); The time.setMinute( 30 ) call executes and returns a reference to time. The remaining expression is interpreted as time.setSecond( 22 ); When the statement is complete, the time is 18for the hour, 30for the minuteand 22 from the second. Note that the calls on line 26 time.setTime( 20, 20, 20 ).toString(); also use the concatenation feature. These method calls must appear in this order in this expression because toStringas defined in the class does not return a reference to a Time4 object. Placing the call to toString before the call to setTime causes a syntax error. Note that toStringreturns a reference to a Stringobject. Therefore, a method of class Stringcould be concatenated to the end of line 26. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01
Note: If you are looking for best quality webspace to host and run your tomcat application check Vision personal web hosting services

Leave a Reply