ghifariastaudi

Untitled

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