为什么将对最终类实例的引用声明为最终的?
第二行的意义是什么:
public final class A {}
final A obj1=new A();
如果 A
已经是不可变的,为什么有人可能想让 obj1
最终? (只是为了让它坚持唯一的内存引用?)。
What is significance of second line :
public final class A {}
final A obj1=new A();
If A
is a already immutable, why would one possibly want to make obj1
final? (just to make it stick to a unique memory reference? ).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
第一行中的
final
意味着该对象已关闭以进行扩展......即您不能对其进行子类化。第二行中的
final
表示您无法重新分配该变量。final
in the first line means that the object is closed for extension...i.e. you can't subclass it.final
in the second line means you can't reassign the variable.首先,
A
并不是不可变的,只需将其声明为final
即可。那么,final 变量就不能被改变。如果 obj1 是一个字段,则这会强制执行可变性(与最终类不同)。
如果它是局部变量,则意味着您可以在匿名类中安全地使用它(否则编译器无法确定在执行匿名类主体之前/期间它有时不会发生变化)
First,
A
is not immutable of you just declare itfinal
.Then, final variables cannot be changed. If
obj1
is a field this enforces mutability (unlike thefinal class
).If it is a local variable it means you can safely use it in anonymous classes (otherwise the compiler can't be sure it won't get change sometimes before/while the anonymous class body is executed)