“最终"是怎么来的?Java中的关键字工作?(我仍然可以修改一个对象.) [英] How does the "final" keyword in Java work? (I can still modify an object.)

查看:16
本文介绍了“最终"是怎么来的?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?

推荐答案

您始终可以初始化一个 final 变量.编译器确保您只能执行一次.

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

请注意,对存储在 final 变量中的对象调用方法与 final 的语义无关.换句话说: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天全站免登陆