在Java中,我們可以在不初始化的情況下宣告final變數嗎?
在Java中,**final** 是一個訪問修飾符,可以用於欄位、類和方法。
- 當一個方法是final時,它不能被重寫。
- 當一個變數是final時,它的值不能被進一步修改。
- 當一個類是final時,它不能被擴充套件。
在不初始化的情況下宣告final變數
如果你聲明瞭一個final變數,之後你不能修改或為其賦值。此外,與例項變數不同,final變數不會用預設值初始化。
因此,*必須在宣告final變數後立即對其進行初始化*。
但是,如果你嘗試在不初始化的情況下宣告final變數,則會生成一個編譯錯誤,提示“變數variable_name在預設建構函式中未初始化”。
示例
在下面的Java程式中,Student類包含兩個final變數name和age,並且它們沒有被初始化。
public class Student {
public final String name;
public final int age;
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:3: error: variable name not initialized in the default constructor private final String name; ^ Student.java:4: error: variable age not initialized in the default constructor private final int age; ^ 2 errors
為了解決這個問題,你需要初始化宣告的final變數,如下所示:
示例
public class Student {
public final String name;
public final int age;
public 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();
}
}輸出
Name of the Student: Raju Age of the Student: 20
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP