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 created

  • 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:

 

 

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 these variables with direct access
                    (e.g.: objRef.k = 4) ???

How to make immutable objects in Java
 

Prevent update by direct access: define all instance variables as private

 

 

We usually add accessor method and mutator method for the 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:

 

 

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

How to make immutable objects in Java
 

Why is object not immutable ?   we can update the variable radius thorugh objRef

 

 

This statement will update the radius variable:   objRef.getRefVarC().radius = 9999;

How to make immutable objects in Java
 

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 !

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();
              
              System.out.println(s1);  // "abc", unchanged !
              System.out.println(s2);
          }