English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Properties of immutable class objects cannot be modified after initialization. For example, String is an immutable class in Java. We can create an immutable class according to the following given rules.
Declare the class as final-The class should be declared as final to prevent extension.
Declare each field as final-Each field should be declared as final to prevent modification after initialization.
Create getter methods for each field.−Create a public getter method for each field. Fields should be private.
Each field has no setter method.−Do not create public setter methods for any fields.
Create a parameterized constructor-Such a constructor will be used to initialize the properties once.
In the following example, we create an immutable class Employee.
public class Tester { public static void main(String[] args) { Employee e = new Employee(30, "Robert"); System.out.println("Name: " + e.getName() +", Age: " + e.getAge()); } } final class Employee { final int age; final String name; Employee(int age, String name) { this.age = age; this.name = name; } public int getAge() { return age; } public String getName() { return name; } }
Output Result
Name: Robert, Age: 30