0

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;
    }
}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
kautom
  • 29
  • 3
  • 1
    Check description of `final` keyword here https://www.geeksforgeeks.org/final-keyword-in-java/. Here is what happens: If the final variable is a reference, this means that the variable cannot be re-bound to reference another object, but the internal state of the object pointed by that reference variable can be changed i.e. you can change field values of the class instance assigned to the final field. – Sergei May 08 '22 at 00:52
  • Fundamentally, you're missing the distinction between a variable and an object. 'final' is a property of the variable, not of any object the variable might refer to. – dangling else May 08 '22 at 03:16

3 Answers3

3

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.

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
1

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.

0

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

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216