为什么实例变量是最终的? [英] Why instance variable to be final?

查看:153
本文介绍了为什么实例变量是最终的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了这个问题不可变对象,并留下了关于不可变对象和最终字段的问题:

I read this question about immutable objects and was left with a question regarding immutable objects and final field:

为什么我们需要不可变类中的实例变量为final?

Why do we need instance variable in immutable class to be final?

例如,考虑这个不可变类:

For example, consider this immutable class:

public final class Immutable 

{

  private final int someVal;

  public Immutable(int someVal)
 {

    this.someVal= someVal;
  }

  public int getVal() {

    return val;
}

}

如果在上面的代码中有没有set方法,实例变量只在构造函数中设置,为什么要求实例变量被声明为final?

If in the above code there is no set methods and the instance variable is set only within the constructor, why is it required that the instance variable is declared final?

推荐答案

没有要求这样做变量 final 。但是,如果您明确打算永远不要更改变量,那么将它设为 final 通常是一种好习惯,因为这不仅强制执行对打字错误或其他的不变量错误,但也宣称它是不可变的意图,例如,其他程序员或你自己。

There is no requirement as such to make the variable final. However, when it is true that you explicitly intend to never change the variable, it is often good practice to make it final, since that not only enforces the invariant against typos or other mistakes, but also declares the intent that it be immutable to, eg., other programmers or yourself.

如果变量是 public ,那么你肯定需要把它设为 final ,以确保接口代码不能改变它的值。

If the variable were public, then you would strictly need to make it final in order to ensure that interfacing code cannot change its value.

请注意,您链接的问题并不直接相关,因为它讨论的 final ,而不是变量。创建一个类 final 意味着它不能继承,而不是它是不可变的。然而,在制作不可变对象时,肯定有一个案例需要注意该问题的内容及其答案;但它仍是一个单独的问题。

Do note that the question you link is not directly related, however, as it discusses classes that are final, rather than variables. Making a class final means that it cannot be inherited from, not that it is immutable. There is certainly a case to be made for taking heed of the contents of that question and its answer when making immutable objects, however; but it is a separate question nonetheless.

这篇关于为什么实例变量是最终的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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