Immutable Class in Java By Example

Immutable is a type of class that once created, its content can’t be change. To makeĀ  your class Immutable, you have to:

  1. Declare your Class as final. This is to prevent other class from extending. See Image#1
  2. Properties must be declared as final. This is to prevent from setting their values after instantiation. See Image#2
  3. Provide a getter methods for properties.
  4. No setters methods for properties.
  5. Optional: Parameterized constructor. This is where you can set the value of your class properties.

Image#1: Error when extending.

Image#2: Error when setting new value

Full example of Immutable Class in Java.


Leave a Reply

Your email address will not be published. Required fields are marked *