We know that the final keyword creates a constant reference to an object. For example:
final Object object = new Object();
However, in this case , only the reference to the object is fixed and cannot be changed during the execution runtime of the program. I may still call setter methods on this object and alter the values of its data members. Is there a way I can prevent this in Java (equivalent of const in C++) ?
I understand a way where I should not define setters to this object class or should allow setting of values only once, but what if I want to pass this object as an argument to a function and do not want that function to alter values of this object’s data members. I may still want to alter the values outside the function.
What should be the function prototype in that case?
The trick is to define a read-only interface to the object, and put the setters only into the class, like this:
At this point, you can access
objas read-only through its interface. If you need to set properties, castobjtoMutableClass, and call the setters.