Immutable objects

  • Recall that objects have:

      1. Properties (that are represented by instance variables in an object)

      2. Actions (that are represented by instance methods in an object)


  • Immutable objects:

      • An immutable object is an object where its properties cannot be changed after it is instantiated

        I.e.: the values in the instant variables are constants

  • Why we want to have immutable objects:

      • Some computer applications are used to record a history of events which are represented by objects

      • The "historical objects" must not be changed !!!

How to make immutable objects in Java
 

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

How to make immutable objects in Java
 

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)

How to make immutable objects in Java
 

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

How to make immutable objects in Java
 

However:   a mutator method will allow other classes to update the private variables

 

 

Therefore:   immutatible objects must not have any mutator methods !

How to make immutable objects in Java
 

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

How to make immutable objects in Java
 

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) ?

How to make immutable objects in Java
 

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

You have used immutable objects before...

  • The String class in Java will create immutable String objects !!!

  • The String class only has methods that construct a new String from an input string

    The input string is not updated.

  • Example:

          public static void main(String[] args)
          {
              String s1 = "abc";
              String s2 = s1.toUpperCase();  // Does not update s1
              
              System.out.println(s1);        // s1 = "abc", unchanged !
              System.out.println(s2);
          }