Timo_

ThisTest

Oct 11th, 2020
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.70 KB | None | 0 0
  1. // Fig. 8.4: ThisTest.java
  2. // this used implicity and explicitly to refer to members of an object.
  3.  
  4. public class ThisTest
  5. {
  6.     public static void main( String[] args)
  7.     {
  8.         SimpleTime time = new SimpleTime( 15, 30, 19 );
  9.         System.out.println( time.buildString() );
  10.     } // end main
  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" refrence 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
  26.         this.minute = minute; // set "this" object's minute
  27.         this.second = second; // set "this" object's second
  28.     } // end SimpleTIme constructor
  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(),
  35.             "toUniversalString()", toUniversalString() );
  36.     } // end method buildString
  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.         // becaus methos does not have local vairables with same
  43.         // names as instance variables
  44.         return String.format( "%02d:%02d:%02d",
  45.             this.hour, this.minute, this.second );
  46.     } // end method to Universal String
  47. } // end class SimpleTime
Advertisement
Add Comment
Please, Sign In to add comment