为什么 Java 不允许在构造函数中初始化 static final 变量?
如果你把变量声明为 static 和 final,并且需要在声明时或在 static 块中对其进行初始化。如果你尝试在构造函数中对其进行初始化,编译器会认为你正试图重新分配值,并会生成编译时错误——
示例
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
要使此程序起作用,你需要在静态块中初始化最终静态变量,如下所示:
示例
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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP