- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to create the immutable class in Java?
An immutable class object's properties cannot be modified after initialization. For example String is an immutable class in Java. We can create a immutable class by following the given rules below.
Make class final − class should be final so that it cannot be extended.
Make each field final − Each field should be final so that they cannot be modified after initialization.
Create getter method for each field. − Create a public getter method for each field. fields should be private.
No setter method for each field. − Do not create a public setter method for any of the field.
Create a parametrized constructor − Such a constructor will be used to initialize properties once.
In following example, we've created a immutable class Employee.
Example
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
Name: Robert, Age: 30
- Related Articles
- How to create immutable class in Java?
- How to create an immutable class in Java?
- How to create an immutable class with mutable object references in Java?\n
- How to create an immutable set in Java?
- Why String class is immutable or final in Java?
- Factory method to create Immutable List in Java SE 9
- Factory method to create Immutable Map in Java SE 9
- Factory method to create Immutable Set in Java SE 9
- Create and demonstrate an immutable collection in Java
- How to initialize immutable collections in Java 9?
- How to create your own helper class in Java?
- How to create an object from class in Java?
- How to make elements of array immutable in Java?
- Factory method to create Immutable List in android?
- Factory method to create Immutable Set in android?

Advertisements