'Are the fields of a final member variable changing values? [duplicate]
For example, we have a final member variable type Cat. Inside the constructor we initialize this variable with a specific instance of a Cat myCat. If we change the myCat.age field does it changes at the final member variable too or it keeps the same value (age) as the time initialized?
public class Aclass {
final Cat myCat;
public Aclass(Cat myCat) {
this.myCat = myCat;
}
}
Solution 1:[1]
Writing final Cat myCat; means you can't change which Cat object myCat references, once the constructor has finished running. But you can certainly call methods of the Cat, like myCat.setAge(15);, subject to the usual access rules. So the fields of the Cat object can certainly change their values. The only thing that can't change is which Cat you have.
Solution 2:[2]
You cannot change cat value like cat = newcat, because cat is final. You can change properities like cat.age(newvalue) because there is a constructor.
Solution 3:[3]
If we change the
myCat.agefield does it changes at thefinalmember variable too or it keeps the same value (age) as the time initialized?
This presumably refers to some code like this:
Cat murgatroyd = ...
Aclass ac = new Aclass(murgatroyd);
ac.myCat.age = 21;
where Aclass is as per your question and Cat has a (non-final, non-private) integer field called age. The myCat field is final, as per your code.
The age value changes.
Declaring a variable to be final does not make the object that the variable refers to constant. The only thing that final modifier "freezes" is the reference value held in the variable itself.
The reference in myCat doesn't change.
An assignment to myCat.age is not an (attempted) assignment to the myCat variable itself. This assignment wouldn't change the myCat variable (to point to a different Cat) even if myCat was not declared as final. That's not what field assignment means in Java ...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Dawood ibn Kareem |
| Solution 2 | |
| Solution 3 |
