English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this example, we will learn how to create an immutable class in Java.
To understand this example, you should understand the followingJava programmingTopic:
final class Immutable { private String name; private int date; Immutable(String name, int date) { //Initialize immutable variables this.name = name; this.date = date; } //private getter method public String getName() { return name; } public int getDate() { return date;} } } class Main { public static void main(String[] args) { //Create an immutable object Immutable obj = new Immutable("w3codebox, 2011); System.out.println("Name: " + obj.getName()); System.out.println("Date: " + obj.getDate()); } }
Output Result
Name: w3codebox Date: 2011
In Java, immutable classes are those whose values do not change. To create an immutable class, please note here:
The class is declared as final, so it cannot be extended
Class members name and date are declared as private, so they cannot be accessed from outside the class
Does not contain any setter methods, so external classes cannot change class members
getter methods return a copy of the class member
Class members are initialized using the constructor