How can we Make a Class as Immutable ?

Discussion in 'Object Oriented Concepts' started by vbraojava, Sep 12, 2008.

  1. vbraojava

    vbraojava New Member

    In order to make a Class Immutable we must restrict changing the state of the Class object by any means. This in turn means avoiding an assignment to a variable. We can achieve this through a final modifier. To further restrict the access we can use a private access modifier. Do not provide any method where we modify the instance variables.

    Somebody can create the SubClass, that can contain methods, which over ride our base class (Immutable Class) methods. Here he can change the variable values.
    - So to avoid that make the Methods in the Class also final. Or a better approach is to make the Immutable Class itself final. Hence cannot make any sub classes, so no question of over ridding.
  2. anneroberts

    anneroberts Member

    Declare the chic as final so it can't be extended.
    Make all fields clandestine so that absolute admission is not allowed.
    Don't accommodate setter methods for variables.
    Make all arbitrary fields final so that it's amount can be assigned alone once.

Share This Page