- 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
Advertisements