初始化的不可变的最终字段是否应该是静态的? [英] Should initialized final fields that are immutable always be made static?

查看:121
本文介绍了初始化的不可变的最终字段是否应该是静态的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否存在非空/初始化不可变最终字段的合法用例。

I was wondering if there would ever be a legitimate use case for non-blank/initialized immutable final fields.

换句话说:

class Foo {
  private final String bar = "bar";
}

Versus

class Foo {
  private static final String BAR = "bar";
}


推荐答案

在大多数情况下回答是:取决于

Answer, as in most cases is: it depends.

使它成为 static 是什么意思?实际上,它意味着让所有实例使用该字段的相同值

What does it mean to make it static? Effectively it means to let all instances use same value of that field.

大多数情况下,不可变对象可以在所有实例之间共享而不会出现问题。就像在这种情况下一样,使其成为静态的,因为您希望类的所有实例都使用该字段的相同

Most of the time immutable object could be shared among all instances without problems. Like in this case it makes sense to make it static since you want all instances of your class to use same value of that field.

但不要忘记即使对象是不可变的,它仍然具有可变属性,如 monitor 。让我们说你的班级有

But lets not forget that even if object is immutable it still has mutable property like monitor which is used in synchronization mechanisms. Lets say your class have

private final Object lock = new Object(); 

并且每个实例都应该使用自己的 lock 同步对象(如 synchronize(lock){...} )。尽管 Object 是不可变的,但是 lock static不是我们想要的(值 lock 不应该共享,但每个实例的单独

and each instance is supposed to use its own lock object for synchronization (like synchronize(lock){...}). Despite the fact that Object is immutable, making lock static is not what we want (value of lock should not be shared, but separate for each instance).

这篇关于初始化的不可变的最终字段是否应该是静态的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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