Final Object in Java
In Java, final is a keyword that ensures immutability of primitive types, methods, variables classes, etc. It is treated as non-accessible modifier. If we want to use the final keyword, we must specify it before a variable, method, and class. It restricts us to access the variable, method, and class. What if we want to make object as final? So, in this section, we will discuss the use of final keyword with object in Java. Also, we will discuss the difference between final and immutable object.
If we use the final keyword with an object, it means that the reference cannot be changed, but its state (instance variables) can be changed.
Making an object reference variable final is a little different from a final variable. In that case object fields can be changed but the reference can't be changed. Note that it is applicable to collections, also.
When a collection marked as final, it means only its reference can't be changed but values can be added, deleted or modified.
The following code snippet demonstrates how to declare final object.
If we instantiate the class Demo, we would not able to assign other value to the attribute obj because it is final.
Let's understand the concept through a Java program.
The value is: 11
We are easily getting and setting value of a final object even if it is declared as final. But the following is not allowed.
Final Object Vs. Immutable Object
In Java, final and immutable object are not the same. There is a slight difference between them.
The final keyword in Java used before a variables, methods, and class that makes the them immutable or unchangeable. The final keyword restricts the user to use variables, methods, and class. It is applicable for all the types of variables such as for instance variable, static variable, and local variable. When a variable declared as final and assigned a value, we can't change the value of the variable. The final method can't be overridden by the child class. A class that is declared final cannot be extended. In case of final object, fields can be changed but the reference can't be changed.
Note: In case of final object, the values in memory are references to the object not the actual objects.
Immutability means once we create an object, we are not allowed to change the content of that object. If we try to change the content and the alteration is successfully done with those changes, in such a case, a new object will be created. If there are no changes in the content, the existing object will be reused.
The following Java program demonstrate the concept of final and immutability.
In the above Java program, we observe the following points:
Next TopicJava OCR