我們能否在 Java 中使用 this 關鍵字呼叫方法?


在 Java 中,用作當前物件的引用的 "this" 關鍵字存在於例項方法或建構函式中。是的,你可以使用它呼叫方法。但是,你應該僅從例項方法(非靜態)呼叫它們。

舉例說明

在以下示例中,Student 類有一個私有變數 name,帶有 setter 和 getter 方法,使用 setter 方法,我們為 main 方法中的 name 變數賦予值,然後,我們在例項方法中使用"this"關鍵字呼叫 getter (getName) 方法。

public class ThisExample_Method {
   private String name;
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public void display() {
      System.out.println("name: "+this.getName());
   }
   public static void main(String args[]) {
      ThisExample_Method obj = new ThisExample_Method();
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the name of the student: ");
      String name = sc.nextLine();
      obj.setName(name);
      obj.display();
   }
}

輸出

Enter the name of the student:
Krishna
name: Krishna

更新日期:30-Jul-2019

3 千 + 次觀看

開啟你的職業生涯

完成課程,即可獲得認證

開始學習
廣告