|
Let's figure out how to make an object immutable:
There are 2 kinds of instance variables inside an object....
An instance variable can be: (1) a primitive type variable or (2) a reference type variable
Question:
How do we
prevent
other classes from
updating these
variables
with direct access
(e.g.:
objRef.k = 4) ???
Prevent update by direct access: define all instance variables as private
We usually add accessor method and mutator method for the instance variables...
However: a mutator method will allow other classes to update the private variables
Therefore: immutatible objects must not have any mutator methods !
Initial design of immutable objects:
Key points: (1) private instance variables and (2) do not have mutator methods
However: there is still one way to update variables through variable objRef...
Why is object not immutable ? we can update the variable radius thorugh objRef
This statement will update the radius variable: objRef.getRefVarC().radius = 9999;
The design of immutable objects:
Key points: (1) private instance variables and (2) do not have mutator methods
Also: (3) do not have accessor methods that return a reference to an object that has public data fields !
|