Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why my code not giving compile error?

Tags:

java

In the below code i am assigning data to final object .But not getting the compile error .

class Name {
    private String name;

    public Name (String s) {
        this.name = s;
    }

    public void setName(String s) {
        this.name = s;
    }
}

private void test (final Name n) {
    n.setName("test");//here exception coming but not giving compile error
}

2 Answers

Because final applies to the reference n, not the object that n refers to.

So you won't be able to do this:

n = new Name("test");
like image 148
Oliver Charlesworth Avatar answered Mar 30 '26 02:03

Oliver Charlesworth


From Java Language Specification:

Once a final variable has been assigned, it always contains the same value. If a final variable holds a reference to an object, then the state of the object may be changed by operations on the object, but the variable will always refer to the same object.

So it is OK to manipulate state of object pointed by n

private void test(final Name n) {
    n.setName("test");
}

but you can't make n to store another object

private void test(final Name n) {
    n = new Name("test"); //Can't do this
}
like image 44
Pshemo Avatar answered Mar 30 '26 02:03

Pshemo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!