在java中将对象声明为final [英] Declaring object as final in java

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

问题描述

有人可以澄清以下代码的重要性。

Can someone clarify the significance of the below code.

class A
{
    int i = 10;

    public void setI(int b)
    {
        i = b;
    }

    public int getI()
    {
        return i;
    }
}

class Test
{    
    public static void main(String args[]) throws Throwable
    { 
        final A ob = new A();
        ob.setI(10);
        System.out.println(ob.getI());
    }
}

对象A被声明为final,但我可以更改此对象的实例变量的值,并还检索更新的值。那么将对象声明为final是什么意义。
我知道将原始数据类型声明为final,这使得该变量保持不变。

The object A is declared as final, but I can change value of this object's instance variable and also retrive the updated value. So what are the significance of declaring an object as final. I am aware about declaring primitive datatype as final, which makes that variable constant.

推荐答案

ob将无法引用任何其他对象:最终关键字

ob will not be able to reference any other object : final keyword.

无法重新分配。但你可以改变它的内部(它是可变的,如果它是最初的)。
所以这样做:

It can not be reassigned. But you can change its internals (it is mutable, if it was originally). So this works :

  final A ob = new A();
  ob.setI(6)

但这不是:

  final A ob = new A();
  ob = new A();

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

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