420 Object-Based Programming (Graphic web design) Chapter 8 11 public class
420 Object-Based Programming Chapter 8 11 public class ThisTest { 12 13 // test class SimpleTime 14 public static void main( String args[] ) 15 { 16 SimpleTime time = new SimpleTime( 12, 30, 19 ); 17 18 JOptionPane.showMessageDialog( null, time.buildString(), 19 “Demonstrating the “this” Reference”, 20 JOptionPane.INFORMATION_MESSAGE ); 21 22 System.exit( 0 ); 23 } 24 25 } // end class ThisTest 26 27 // class SimpleTime demonstrates the “this” reference 28 class SimpleTime { 29 private int hour, minute, second; 30 31 // constructor uses parameter names identical to instance 32 // variable names, so “this” reference required to distinguish 33 // between instance variables and parameters 34 public SimpleTime( int hour, int minute, int second ) 35 { 36 this.hour = hour; // set “this” object’s hour 37 this.minute = minute; // set “this” object’s minute 38 this.second = second; // set “this” object’s second 39 } 40 41 // call toString explicitly via “this” reference, explicitly 42 // via implicit “this” reference, implicitly via “this” 43 public String buildString() 44 { 45 return “this.toString(): ” + this.toString() + 46 “ntoString(): ” + toString() + 47 “nthis (with implicit toString() call): ” + this; 48 } 49 50 // convert SimpleTime to String format 51 public String toString() 52 { 53 DecimalFormat twoDigits = new DecimalFormat( “00″ ); 54 55 // “this” not required, because toString does not have 56 // local variables with same names as instance variables 57 return twoDigits.format( this.hour ) + “:” + 58 twoDigits.format( this.minute ) + “:” + 59 twoDigits.format( this.second ); 60 } 61 62 } // end class SimpleTime Fig. 8.17 Using the thisreference implicitly and explicitly (part 2 of 3). Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/3/01