集册 Java实例教程 'this'关键字隐式和显式地用于引用对象的成员。

'this'关键字隐式和显式地用于引用对象的成员。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

670
提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
'this'关键字隐式和显式地用于引用对象的成员。

public class Main 

{
/* 
*来 自
 N o w J a v a . c o m
*/

   public static void main(String[] args)

   {

      SimpleTime time = new SimpleTime(15, 30, 19);

      System.out.println(time.buildString());

   } 

} 


// class SimpleTime demonstrates the "this" reference

class SimpleTime 

{

   private int hour; // 0-23

   private int minute; // 0-59

   private int second; // 0-59 


   // if the constructor uses parameter names identical to /*来 自 N o w  J a v a  . c o m*/

   // instance variable names, the "this" reference is 

   // required to distinguish between the names

   public SimpleTime(int hour, int minute, int second)

   {

      this.hour = hour; // set "this" object's hour

      this.minute = minute; // set "this" object's minute

      this.second = second; // set "this" object's second

   } 


   // use explicit and implicit "this" to call toUniversalString

   public String buildString()

   {

      return String.format("%24s: %s%n%24s: %s", 

         "this.toUniversalString()", this.toUniversalString(),

         "toUniversalString()", toUniversalString());

   } 


   
展开阅读全文