我們能從 java 中的方法返回此關鍵字嗎?


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

返回“this”

是的,您可以在 Java 中返回 this,即以下語句有效。

return this;

當您從某個方法返回 “this” 時,將返回當前物件。

範例

在以下 Java 範例中,Student 類有兩個私有變數:name 和 age。從 setValues() 方法中,我們將從使用者那裡讀取值並將其分配給這些(例項)變數,同時返回當前物件。

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

輸出

Enter the name of the student:
Krishna Kasyap
Enter the age of the student:
21
name: Krishna Kasyap
age: 21

更新時間: 2020 年 6 月 29 日

6K+ 瀏覽次數

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.