为什么 Java 不允许在构造函数中初始化静态 final 变量?
javaobject oriented programmingprogramming更新于 2024/8/26 10:53:00
如果您将变量声明为静态和 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
为了使该程序正常工作,您需要在静态块中初始化最终静态变量,如下所示 −
示例
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