final in Java
Understanding significance of final in Java
Final modifier in Java spans its influence on
Type (inner class , Enums) | YES |
field | YES |
methods | YES |
Key Take Aways
Type :
- A final class is one which can be not be inherited any further.
- A final class is a class which has all its method defined , there are no abstract methods in the class.
- A final class signifies the end of the inheritance chain .
- A final class is the opposite of abstract class.
Field
- Final modifier when applied to a field signifies the field cannot change its value once initialized.
- The initialization can be done via a initializer or constructor at time of object instantiation.
- Final modifier when applied to the field signifies that the value cannot be changed.
- If the final field is of primitive type the value of the variable cannot be changed.
- if the field field is of Class Type , then the reference is bound to the object for the lifetime.The Object can change its state though
Methods:
- Final modifier when applied to method means it cannot be overriden in any of the subclass.
[addToAppearHere]
Code:
package com.big.data.java.modifiers;
import java.util.HashMap;
import java.util.Map;
final class ParentClass {
int a;
};
// public class ChildClass extends ParentClass not possible as parentClass is final
public class FinalDemo {
// value set as part of initialization
final int a = 10;
// value needs to be set in constructor
final Map<String, String> mapReference;
public FinalDemo() {
//a = 20; not possible as 10 has been set in the intialization
mapReference = new HashMap<>();
}
public void changeMap() {
// mapReference = new HashMap<>(); not possible as mapReference is final and has been initialized in constructor.
// Object new HashMap<>() can change its state but reference needs to keep pointig at mapReference = new HashMap<>();
mapReference.put("1", "1");
//a = 20; primitive type cannot change its value as it is final
}
}