What is final in Java?


What is final in Java?
What is final in Java?
Final is the modifiers applicable for classes, methods, and variables.Â
- The main advantage of final keyword is we can achieve security and we can provide the unique implementation.
- Final keyword improves performance. Not just JVM can cache final variable but also application can cache frequently use final variables.
- Final variables are safe to share in multi-threading environment without additional synchronization overhead.
- But the main disadvantage of a Final keyword is we are missing key benefits of OOPS.
Final Method
- Whatever method parent has by default available to child throw inheritance.
- If the child not satisfied with parent method implementation then the child is allowed to redefine the method based on its requirement. This process is called overriding.
- If the parent class method is declared as final then we can’t override that method in child class because its implementation is final.
- A final method cannot be overridden
Final Class
- If a class declared as final we can’t extend the functionality of that class ie we can’t create the child class for that class ie inheritance is not possible for final classes.
- Every method present in the final class is always final by default but every variable present inside final class need not be final.
- The other use of final with classes is to create an immutable class like the predefined String class. You can not make a class immutable without making it final.
- A final class cannot be subclassed
Final Instance Variable
- If the value of the variable is varied from object to object such type of variables is called instance variables.
- For every object, a separate copy of instance variables will be created.
- For instance variable, we are not required to perform initialization explicitly. JVM will always provide default values(Zero).
- If the instance variable declared as final then compulsory we have to perform initialization explicitly. Whether we are using or not and JVM won’t provide default values.
- The only difference between a normal variable and a final variable is that we can re-assign value to a normal variable but we cannot change the value of a final variable once assigned.
- Final variables are nothing but constants. We cannot change the value of a final variable once it is initialized.
Rule:-
- For final instance variable compulsory, we should perform initialization before constructor completion. i.e. The following are various places for initialization.
- At the time of declaration.
- Inside instance block
- Inside constructor.
- These are the only possible place to perform initialization for the final instance variable. If we are trying to perform initialization anywhere else then we will get compile time error.