什么是空白 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