java中的最终对象 [英] final object in java

查看:150
本文介绍了java中的最终对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

何时使用最终版


声明有什么用?对象的最终关键字?例如:

final Object obj = new myclass();


推荐答案

使用final关键字使变量成为你宣布不变。初始分配后,无法重新分配。

Using the "final" keyword makes the the variable you are declaring immutable. Once initially assigned it cannot be re-assigned.

但是,这并不一定意味着变量引用的实例的状态是不可变的,只是引用本身。

However, this does not necessarily mean the state of the instance being referred to by the variable is immutable, only the reference itself.

为什么要在变量上使用final关键字有几个原因。一个是优化,通过将变量声明为final,允许值为 memoized

There are several reasons why you would use the "final" keyword on variables. One is optimization where by declaring a variable as final allows the value to be memoized.

另一种使用final变量的场景是方法中的内部类需要在声明方法中访问变量。以下代码说明了这一点:

Another scenario where you would use a final variable is when an inner class within a method needs to access a variable in the declaring method. The following code illustrates this:

public void foo() {

        final int x = 1;

        new Runnable() {


            @Override
            public void run() {
                int i = x;
            }

        };

}

如果x未被声明为final,则代码将导致编译错误。需要成为最终的确切原因是因为新的类实例可以比方法调用更长,因此需要它自己的x实例。为了避免在同一范围内拥有多个可变变量副本,必须将变量声明为final,以便不能更改。

If x is not declared as "final" the code will result in a compilation error. The exact reason for needing to be "final" is because the new class instance can outlive the method invocation and hence needs its own instance of x. So as to avoid having multiple copies of a mutable variable within the same scope, the variable must be declared final so that it cannot be changed.

一些程序员也提倡使用最终,以防止意外重新分配变量,他们不应该。排序最佳实践类型规则。

Some programmers also advocate the use of "final" to prevent re-assigning variables accidentally where they should not be. Sort of a "best practice" type rule.

这篇关于java中的最终对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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