為什麼建構函式在 Java 中不能是最終 (Final) 的?


無論何時將方法設為最終 (final),都無法重寫它。換言之,無法從子類向超類的最終方法提供實現。

換言之,將方法設為最終的目的是防止從外部(子類)修改方法。

在繼承中,無論何時擴充套件一個類。子類都會繼承超類的所有成員,但建構函式除外。

換句話說,在 Java 中無法繼承建構函式,因此無法重寫建構函式。

因此,在建構函式前寫 final 是沒有意義的。因此,Java 不允許在建構函式前使用 final 關鍵字。

如果嘗試將建構函式設為最終,將會生成一個編譯時錯誤,提示“此處不允許使用修飾符 final”。

示例

在以下 Java 程式中,Student 類有一個最終的建構函式。

 線上演示

public class Student {
   public final String name;
   public final int age;
   public final Student() {
      this.name = "Raju";
      this.age = 20;
   }
   public void display() {
      System.out.println("Name of the Student: "+this.name );
      System.out.println("Age of the Student: "+this.age );
   }
   public static void main(String args[]) {
      new Student().display();
   }
}

編譯時錯誤

編譯時,上述程式會生成以下錯誤。

Student.java:6: error: modifier final not allowed here
   public final Student(){
                ^
1 error

更新日期:2019 年 10 月 15 日

3K+ 次瀏覽

開啟您的 職業

完成課程並獲得認證

開始
廣告