

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Do all properties of an Immutable Object need to be final in Java?
Immutable class/object is the one whose value cannot be modified. For example, Strings are immutable in Java i.e. once you create a String value in Java you cannot modify it. Even if you try to modify, an intermediate String is created with the modified value and is assigned to the original literal.
Defining immutable objects
Whenever you need to create an object which cannot be changed after initialization you can define an immutable object. There are no specific rules to create immutable objects, the idea is to restrict the access of the fields of a class after initialization.
Example
Following Java program demonstrates the creation of a final class. Here, we have two instance variables name and age, except the constructor you cannot assign values to them.
final public class Student { private final String name; private final int age; public Student(String name, int age){ this.name = name; this.age = age; } public String getName() { return this.name; } public int getAge() { return this.age; } public static void main(String[] args){ Student std = new Student("Krishna", 29); System.out.println(std.getName()); System.out.println(std.getAge()); } }
Output
Krishna 29
Is it a must to declare all variables final
No, it is not mandatory to have all properties final to create an immutable object. In immutable objects you should not allow users to modify the variables of the class.
You can do this just by making variables private and not providing setter methods to modify them.
Example
public class Sample{ String name; int age; public Sample(){ this.name = name; this.age = age; } public String getName(){ return this.name; } public int getAge(){ return this.age; } }
- Related Questions & Answers
- Can a final variable be initialized when an object is created in Java?
- Why String class is immutable or final in Java?
- How to create an immutable class with mutable object references in Java?
- What are all the ways an object can be created in Java?
- Do you need any special qualification to be a pharmacist?
- How to create an immutable class in Java?
- How to create an immutable set in Java?
- Do we need forward declarations in Java?
- Why do we need generics in Java?
- Why constructor cannot be final in Java
- Copy all elements of Java HashSet to an Object Array
- Copy all elements of Java LinkedHashSet to an Object Array
- Copy all elements of ArrayList to an Object Array in Java
- Why should a blank final variable be explicitly initialized in all Java constructors?
- Why do we need private methods in an interface in Java 9?