Home > database >  Are the fields of a final member variable changing values?
Are the fields of a final member variable changing values?

Time:05-08

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

CodePudding user response:

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.

CodePudding user response:

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 properities are not final.

CodePudding user response:

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

  • Related