Guest User

Untitled

a guest
Feb 27th, 2017
138
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.86 KB | None | 0 0
  1. /**
  2.  * ThisTest.java
  3.  * this used implicitly and explicitly to refer to members of an object.
  4.  *
  5.  * Ilham Febriyanto
  6.  * 26 February 2017
  7.  */
  8.  
  9. public class ThisTest
  10. {
  11.     public static void main (String[] args)
  12.     {
  13.      SimpleTime time = new SimpleTime (15, 30, 19);
  14.      System.out.println (time.buildString());
  15.     } // end main
  16. } // end class ThisTest
  17.    
  18. // class SimpleTime demonstrates the "this" reference
  19. class SimpleTime
  20. {
  21.     private int hour; // 0 - 23
  22.     private int minute; // 0 - 59
  23.     private int second; // 0 - 59
  24.    
  25.     // if the constructor uses parameter names identical to
  26.     // instance variable names the "this" reference is
  27.     // required to distinguish between the names
  28.     public SimpleTime (int hour, int minute, int second)
  29.     {
  30.         this.hour = hour; // set "this" object's hour
  31.         this.minute = minute; // set "this" object's minute
  32.         this.second = second; // set "this" object's second
  33.     } // end SimpleTime constructor
  34.    
  35.     // use explicit and implicit "this" to call toUniversalString
  36.     public String buildString()
  37.     {
  38.         return String.format ("%24s: %s\n%24s: %s",
  39.             "this.toUniversalString()", this.toUniversalString(),
  40.             "toUniversalString()", toUniversalString());
  41.     } // end method buildString
  42.    
  43.     // convert to String in universal-time format (HH:MM:SS)
  44.     public String toUniversalString()
  45.     {
  46.         // "this" is not required here to access instance variables,
  47.         // because method does not have local variables with same
  48.         // names as instance variables
  49.         return String.format ("%02d:%02d:%02d",
  50.             this.hour, this.minute, this.second);
  51.     } // end method toUniversalString
  52. } // end class SimpleTime
Advertisement
Add Comment
Please, Sign In to add comment