我們是否可以直接在 Java 中的一個方法內呼叫建構函式?


建構函式 類似於方法,當建立類物件時會呼叫建構函式,通常用於初始化類的例項變數。建構函式的名稱與其類相同,並且沒有返回型別。

無需顯式呼叫建構函式,這些建構函式會在例項化時自動呼叫。

Java 中的this 關鍵字是對當前類物件的引用。使用它,你可以引用類的欄位、方法或建構函式。

因此,如果你需要顯式呼叫建構函式,可以使用“this()”對其進行呼叫。

從方法中呼叫建構函式

不,你無法從方法中呼叫建構函式。唯一可以從另一個建構函式的第一行使用 “this()” 或 “super()” 呼叫建構函式的位置是。如果你嘗試在其他位置顯式呼叫建構函式,將會生成一個編譯時錯誤。

示例

import java.util.Scanner;
public class Student {
   private String name;
   private int age;
   Student(){}
   Student(String name, int age){
      this.name = name;
      this.age = age;
   }
   public void SetValues(String name, int age){
      this(name, age);
   }
   public void display() {
      System.out.println("name: "+this.name);
      System.out.println("age: "+this.age);
   }
   public static void main(String args[]) {
      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();
      Student obj = new Student();
      obj.SetValues(name, age);
      obj.display();
   }
}

編譯時錯誤

Student.java:12: error: call to this must be first statement in constructor
   this(name, age);
^
1 error

更新於:2020 年 7 月 2 日

9K 多次瀏覽

開啟你的 事業

完成課程,獲得認證

開始
廣告
© . All rights reserved.