|
Let's figure out how to make an object immutable: instantce variables are updated through a reference:
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
instance variables ?
(e.g.: with
objRef.k = 4;
and with
objRef.c.radius = 4)
To prevent update using the reference variable objRef: define all instance variables as private:
We usually add accessor method and mutator method to manipulate the private 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:
Requirements: (1) private instance variables and (2) do not have mutator methods
However: there is still one way to update instance variables !!!
We can update the variable radius thorugh objRef using: objRef.getRefVarC().radius = 4 !
How can we prevent this access from within the class that we are writing (i.e.: cannot change Circle) ?
Do not provide accessor method for reference data type variables:
Requirements: (1) private instance variables and (2) do not have mutator methods
Also: (3) do not provide accessor methods to objects
|