在Java中,我们使用final带变量的关键字来指定其值不被更改.但我发现你可以改变类的构造函数/方法中的值.同样,如果变量是,static那么它是编译错误.
这是代码:
import java.util.ArrayList;
import java.util.List;
class Test {
private final List foo;
public Test()
{
foo = new ArrayList();
foo.add("foo"); // Modification-1
}
public static void main(String[] args)
{
Test t = new Test();
t.foo.add("bar"); // Modification-2
System.out.println("print - " + t.foo);
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码工作正常,没有错误.
现在将变量更改为static:
private static final List foo;
Run Code Online (Sandbox Code Playgroud)
现在是编译错误.这final真的有用吗?
java常量变量是否有任何命名约定?
通常我们使用名称包含大写字母和下划线(_)的变量.
例如:
public final class DeclareConstant {
public static final String CONSTANT_STRING = "some constant";
public static final int CONSTANT_INTEGER = 5;
}
Run Code Online (Sandbox Code Playgroud)