什麼是空白 final 變數?Java 中的靜態空白 final 變數是什麼?
靜態變數 − 靜態變數也稱為類變數。您可以使用關鍵字宣告一個變數為靜態。一旦您將變數宣告為靜態,無論從它建立了多少個物件,類中都只會有一個副本。
public static int num = 39;
例項變數 − 這些變數屬於類的例項(物件)。它們在類中宣告,但在方法之外。在例項化類時初始化這些變數。可以從該特定類的任何方法、建構函式或塊中訪問它們。
必須使用物件訪問例項變數。即,要訪問例項變數,需要建立類的物件,並使用此物件訪問這些變數。
final − 一旦您宣告一個變數為 final,就不能重新分配值。
空白變數
一個未初始化的 final 變數稱為空白 final 變數。與例項變數一樣,final 變數不會使用預設值初始化。因此,必須在宣告 final 變數後立即初始化它們。
但是,如果您嘗試在程式碼中使用空白變數,則會生成編譯時錯誤。
示例
在以下 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
靜態空白 final 變數
同樣,如果您宣告一個靜態變數為 final 且未初始化,則它被視為靜態 final 變數。
當一個變數同時宣告為 static 和 final 時,您只能在靜態塊中初始化它,如果您嘗試在其他地方初始化它,編譯器會假設您正在嘗試重新分配值並生成編譯時錯誤:
示例
class Data{
static final int num;
Data(int i){
num = i;
}
}
public class ConstantsExample {
public static void main(String args[]) {
System.out.println("value of the constant: "+Data.num);
}
}編譯時錯誤
ConstantsExample.java:4: error: cannot assign a value to final variable num num = i; ^ 1 error
示例
因此,必須在靜態塊中初始化靜態 final 變數。
要使上述程式工作,您需要在靜態塊中初始化 final 靜態變數,如下所示:
class Data{
static final int num;
static{
num = 1000;
}
}
public class ConstantsExample {
public static void main(String args[]) {
System.out.println("value of the constant: "+Data.num);
}
}輸出
value of the constant: 1000
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP