Final Keyword In Java
final is a keyword in java which can be used with instance variables, local variables , methods and classes.
Use of final keyword in java:
1. final variable in java:
A variable declared with final keyword is known as final variable. It may be member variable or local variable. final variables are constants in java and they are generally declared with static keyword. As final variables are treated as constants they can’t reassign. They are initialised at the time of declaration.
Note: Inside Anonymous classes only final variables are accessible.
2. final method in java:
A method declared with final keyword is known as final method.
Note: A final method can be inherited but can’t be override.
3. final class in java:
A class declared with final keyword is known as final class. A final class can’t be inherited.
Note: final method can be inherited.
Note: Abstract class and constructor can’t be final.
4. Blank final variable in java:
A variable declared with final keyword but not initialised at declaration time is known as blank final variable. They are initialised at the time of object creation in constructor and can’t change after that.
5. static blank final variable in java:
A static variable declared with final keyword but not initialised at declaration time is known as static blank final variable. It can be initialised in a static block only.
6. final parameter in java:
A method parameter declared with final keyword is known as final parameter. Its value can’t be changed.
Advantages/Benefits of final keyword:
- 1. Performance: JVM kept in cache if variables, methods and classes are declared final.
- 2. Immutable classes: With the help of final keyword we can made immutable classes.