Do all properties of an Immutable Object need to be final in Java?

Java 8Object Oriented ProgrammingProgramming

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;
   }
}
raja
Published on 06-Aug-2019 07:38:34
Advertisements