How to create an immutable class in Java?

Java 8Object Oriented ProgrammingProgramming

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.

Example

public final class Sample {
   private final String name;
   private final int age;
   public Sample(final String name, final int age) {
      this.name = name;
      this.age = age;
   }
   public int getAge() {
      return age;
   }
   public String getName() {
      return name;
   }
}
raja
Published on 08-Jan-2018 06:03:27
Advertisements