Ch. 02 – Immutable Pattern

Published by

on

Immutable

  • Immutable class’s state doesn’t change after initialization.
    • Class is set as final
    • Field variables are set as final and private
      • Cannot update the field variable’s value
    • No setter methods
      • No methods can update the values
    • Getter method does not return the field variable reference
      • If getter method returns a reference for the object, it can be updated from other places.
  • Immutable methods do not need synchronized keyword added.
    • No synchronized keyword means it’s faster
  • { frozen }: Instance field value doesn’t change after initialized
    • In Java, final keyword supports that
  • { concurrent }: It is safe to be ran from multiple threads at the same time
    • No need to add synchronized keyword to the method as the method doesn’t change the state of shared resources.

Example

  • Person class is immutable
    1. As the class is declared as final class, we cannot create a subclass that inherits Person class.
      • This prevents from field values being updated from subclasses.
    2. As the field values on Person class is declared as final and private, it can only be set from constructor. (No setters)
      • If it is not private, the subclass would be able to update the value, which breaks immutable pattern.

String vs StringBuffer

  • String is immutable class while StringBuffer is a mutable class

final keyword

final Class

  • Can not create subclass of final class.
  • As we we cannot create a subclass of the final class, the methods cannot be overriden as well.

final Method

  • Cannot override final method.

final Field

  • Can be initialized only once.
    1. Using constructor
    2. From declaration

Others

  • final local variable can be initialized only once
  • final method parameter can not be updated because it will be set from the invocation part.

Leave a comment