How to create an immutable class in Java?

A class is said to be immutable when you cannot change its contents after once created.

In general, we change the values of the fields of a class using setter methods, by reassigning the values. We can change the methods by inheriting them.

Therefore, to make a class immutable.

  • The class should be final so that you cannot inherit it.
  • All the properties should be final so that they remain constant.
  • Setter methods should not be created.


public final class Sample {
   private final String name;
   private final int age;
   public Sample(final String name, final int age) { = name;
      this.age = age;
   public int getAge() {
      return age;
   public String getName() {
      return name;