Java 中可以將建構函式宣告為 final 嗎?


建構函式用於在建立物件時初始化物件。從語法上看,它類似於方法。區別在於建構函式與其類具有相同的名稱,並且沒有返回型別。

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

示例

 即時演示

public class Example {
   public Example(){
      System.out.println("This is the constructor of the class example");
   }
   public static void main(String args[]) {
      Example obj = new Example();
   }
}

輸出

This is the constructor of the class example

final 方法

每當你將一個方法設為 final 時,你就不能重寫它。即你不能從子類為父類的 final 方法提供實現。

即,將方法設為 final 的目的是防止從外部(子類)修改方法。

示例

在下面的 Java 程式中,我們嘗試重寫一個 final 方法。

 即時演示

class SuperClass{
   final public void display() {
      System.out.println("This is a method of the superclass");
   }
}
public class SubClass extends SuperClass{
   final public void display() {
      System.out.println("This is a method of the superclass");
   }
}

編譯時錯誤

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

SubClass.java:10: error: display() in SubClass cannot override display() in SuperClass
final public void display() {
                  ^
overridden method is final
1 error

將建構函式宣告為 final

在繼承中,每當你擴充套件一個類時。子類繼承父類所有成員,除了建構函式。

換句話說,建構函式不能在 Java 中被繼承,因此,你不能重寫建構函式。

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

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

示例

在下面的 Java 程式中,Student 類有一個 final 的建構函式。

 即時演示

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

更新於: 2020-06-29

3K+ 瀏覽量

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告