- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 an immutable class in Java?
A class is said to be immutable when you cannot change its contents after once created.
In general, we change the values of the fields of a class using setter methods, by reassigning the values. We can change the methods by inheriting them.
Therefore, to make a class immutable.
- The class should be final so that you cannot inherit it.
- All the properties should be final so that they remain constant.
- Setter methods should not be created.
Example
public final class Sample { private final String name; private final int age; public Sample(final String name, final int age) { this.name = name; this.age = age; } public int getAge() { return age; } public String getName() { return name; } }
- Related Articles
- How to create immutable class in Java?
- How to create the immutable class in Java?
- How to create an immutable class with mutable object references in Java?
- How to create an immutable set in Java?
- Create and demonstrate an immutable collection in Java
- How to create an object from class 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
- How to create and set an Empty Border from BorderFactory class in Java?
- How to create an empty class in Python?
- How to initialize immutable collections in Java 9?
- How to create your own helper class in Java?
- Can we create an object of an abstract class in Java?

Advertisements