Join our newsletter for the latest updates.
Java Program to Create a immutable class

Java Program to Create a immutable class

In this example, we will learn to create an immutable class in Java.

To understand this example, you should have the knowledge of the following Java programming topics:


Example: Java program to create immutable class

final class Immutable {

  private String name;
  private int date;

  Immutable(String name, int date) {

    // initialize the immutable variables
    this.name = name;
    this.date = date;
  }

  // private getter methods
  public String getName() {
    return name;
  }

  public int getDate() {
    return date;
  }

}

class Main {
  public static void main(String[] args) {
    // create object of Immutable
    Immutable obj = new Immutable("Programiz", 2011);

    System.out.println("Name: " + obj.getName());
    System.out.println("Date: " + obj.getDate());
  }
}

Output

Name: Programiz
Date: 2011

In Java, immutable classes are those classes whose values are not changed. To create an immutable class, here

  • class is declared final so it cannot be extended
  • class members name and date are private so cannot be accessed outside of class
  • does not contain any setter methods so outer class cannot change the class members
  • getter method returns the copy of class members
  • class members are initialized using the constructor