为什么将对最终类实例的引用声明为最终的?

发布于 2024-11-18 16:01:03 字数 175 浏览 3 评论 0原文

第二行的意义是什么:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

ま昔日黯然 2024-11-25 16:01:03

第一行中的 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.

蓝天白云 2024-11-25 16:01:03

首先,A 并不是不可变的,只需将其声明为 final 即可。

那么,final 变量就不能被改变。如果 obj1 是一个字段,则这会强制执行可变性(与最终类不同)。

如果它是局部变量,则意味着您可以在匿名类中安全地使用它(否则编译器无法确定在执行匿名类主体之前/期间它有时不会发生变化)

First, A is not immutable of you just declare it final.

Then, final variables cannot be changed. If obj1 is a field this enforces mutability (unlike the final 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)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文