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?
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 ...