“最终”如何? Java中的关键字有效吗? (我仍然可以修改一个对象。) [英] How does the "final" keyword in Java work? (I can still modify an object.)

查看:105
本文介绍了“最终”如何? Java中的关键字有效吗? (我仍然可以修改一个对象。)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,我们使用 final 关键字和变量来指定其值不被更改。
但是我看到你可以改变类的构造函数/方法中的值。同样,如果变量是 static 那么这是一个编译错误。

In Java we use final keyword with variables to specify its values are not to be changed. But I see that you can change the value in the constructor / methods of the class. Again, if the variable is static then it is a compilation error.

这是代码:

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);
  }
}

上面的代码工作正常,没有错误。

Above code works fine and no errors.

现在将变量更改为 static

private static final List foo;

现在是编译错误。这个 final 如何真正起作用?

Now it is a compilation error. How does this final really work?

推荐答案

你总是被允许初始化 最终变量。编译器确保您只能执行一次。

You are always allowed to initialize a final variable. The compiler makes sure that you can do it only once.

请注意,对存储在 final 变量中的对象的调用方法与<$的语义无关C $ C>最终。换句话说: final 只是关于引用本身,而不是引用对象的内容。

Note that calling methods on an object stored in a final variable has nothing to do with the semantics of final. In other words: final is only about the reference itself, and not about the contents of the referenced object.

Java没有对象不变性的概念;这是通过精心设计对象来实现的,并且是一项非常重要的工作。

Java has no concept of object immutability; this is achieved by carefully designing the object, and is a far-from-trivial endeavor.

这篇关于“最终”如何? Java中的关键字有效吗? (我仍然可以修改一个对象。)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆