English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Do all properties of immutable objects need to be final in Java?

Immutable classes/Objects are classes that cannot change their values/Objects. For example, strings are immutable in Java, which means that once a string value is created in Java, it cannot be modified. Even if you try to modify it, a new intermediate string will be created with the modified value and assigned to the original text.

Define immutable objects

Immutable objects can be defined whenever it is necessary to create objects that cannot be changed after initialization. There are no specific rules for creating immutable objects, but the idea is to limit access to class fields after initialization.

Example

The following Java program demonstrates the creation of a final class. Here, we have two instance variables named name and age, except that the constructor 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 Result

Krishna
29

Is it necessary to declare all variables as final

No, not all properties must have the final attribute to create immutable objects. In immutable objects, you should not allow users to modify the class variables.

You can modify them by setting variables as private without providing a setting method to do this.

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;
   {}
{}