在 Java 中宣告 final 方法/建構函式會發生什麼?
每當您把一個方法變為 final 的時候,您就不能重寫它。也就是說您不能在子類中對超類中宣告為 final 的方法的實現進行重寫。
也就是說,把一個方法宣告為 final 的目的是防止它被外部(子類)修改。
即使這樣,如果您仍然嘗試重寫一個 final 方法,編譯器將會產生編譯時錯誤。
示例
interface Person{ void dsplay(); } class Employee implements Person{ public final void dsplay() { System.out.println("This is display method of the Employee class"); } } class Lecturer extends Employee{ public void dsplay() { System.out.println("This is display method of the Lecturer class"); } } public class FinalExample { public static void main(String args[]) { Lecturer obj = new Lecturer(); obj.dsplay(); } }
輸出
Employee.java:10: error: dsplay() in Lecturer cannot override dsplay() in Employee public void dsplay() { ^ 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
廣告