什麼是 Java 中的 “this” 引用?


在 Java 中,this 關鍵字用作對當前類物件的引用,它在例項方法或建構函式中使用。利用 this 可以引用類的成員,如建構函式、變數和方法。

使用“this”可以 −

  • 在建構函式或方法中,將例項變數與同名區域性變數區分開來。

class Student {
   int age;
   Student(int age) {
      this.age = age;
   }
}
  • 在同一類中呼叫一種型別的建構函式(帶引數的建構函式或預設的建構函式)。這稱為顯式建構函式呼叫。

class Student {
   int age
   Student() {
      this(20);
   }
   Student(int age) {
      this.age = age;
   }
}

示例

 即時演示

public class This_Example {
   // Instance variable num
   int num = 10;
   This_Example() {
      System.out.println("This is an example program on keyword this");
   }
   This_Example(int num) {
      // Invoking the default constructor
      this();
      // Assigning the local variable num to the instance variable num
      this.num = num;
   }
   public void greet() {
      System.out.println("Hi Welcome to Tutorialspoint");
   }
   public void print() {
      // Local variable num
      int num = 20;
      // Printing the local variable
      System.out.println("value of local variable num is : "+num);
      // Printing the instance variable
      System.out.println("value of instance variable num is : "+this.num);
      // Invoking the greet method of a class
      this.greet();
   }
   public static void main(String[] args) {
      // Instantiating the class
      This_Example obj1 = new This_Example();
      // Invoking the print method
      obj1.print();
      // Passing a new value to the num variable through parametrized constructor
      This_Example obj2 = new This_Example(30);
      // Invoking the print method again
      obj2.print();
   }
}

輸出

This is an example program on keyword this
value of local variable num is : 20
value of instance variable num is : 10
Hi Welcome to Tutorialspoint
This is an example program on keyword this
value of local variable num is : 20
value of instance variable num is : 30
Hi Welcome to Tutorialspoint

更新時間:29-6-2020

2K+ 瀏覽次數

開啟您的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.