Declaring object as final in java

2019-03-12 17:12发布

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());
    }
}

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.

标签: java oop final
7条回答
The star\"
2楼-- · 2019-03-12 17:49

Well, in case of object, the value of reference is address to objects. So value of ob will be address to the object created by new A();that will be final and you will not be able to change its value. meaning there by, You can't assign a new object to this reference.

You can't write this way.

final A ob = new A();

ob= new A(); // not allowed
查看更多
登录 后发表回答