[Solved] Reassign reference returned by a method


It’s simply how Java is specified. From JLS Sec 15.26, the grammar of the assignment is given by:

Assignment:
    LeftHandSide AssignmentOperator Expression

LeftHandSide:
    ExpressionName 
    FieldAccess 
    ArrayAccess

So the LHS has to be either a variable, a field or an array element. Anything else is invalid syntax.

The reason why you can’t reassign a method’s return value is because Java is pass-by-value, always. The “reference” returned by the getBar() method isn’t the Foo.bar field, it’s a effectively new variable which also points to the same object as the Foo.bar field. So, reassigning that variable has no effect on the value of the Foo.bar field.

And since that “variable” would only exist while the expression is being evaluated, there is no point in allowing it: you may as well just use the RHS’s value directly instead.

It’s no different from the following:

Object a = new Object();
Object b = a;      // a and b now refer to the same object.
b = new Object();  // This reassigns b, but not a.

2

solved Reassign reference returned by a method