Final Keyword
The final keyword in java is used to restrict the user. It can be used with:
- Variable
- Method
- Class
Final Variable
Final variable is a constant variable, as its value can’t be modified once initialized.
The initialization of the final variable can be done in 3 ways
- At the time of declaration
- Inside the constructor
- inside static block // Only if we have a final static variable
If the final variable is a reference, we cannot re-assign it to another object but can change the internal values. Below is an example to demonstrate this. This property of final is called non-transitivity.
Example:
import java.util.Arrays;
public class FinalKeywordExample {
static {
staticFinalVariable = 1;
}
FinalKeywordExample() {
finalVariableWithoutInit = 2;
}
private static final int staticFinalVariable;
private final int finalVariableWithoutInit;
private final int finalVariable = 3;
private final int[] array = new int[] {1, 2, 3};
public static void main(String[] args) {
FinalKeywordExample finalKeywordExample = new FinalKeywordExample();
finalKeywordExample.array[2] = 4;
//finalKeywordExample.array = new int[] {1, 2, 3}; // This is not possible
System.out.println(Arrays.toString(finalKeywordExample.array));
}
}
Final Method
Final methods can not be overridden by the child class.
Example:
class Parent {
final void finalMethod() {
System.out.println("Final Method");
}
}
class Child extends Parent {
void finalMethod() {} // Not Possible
}
Final Class
Final class cannot be extended. Wrapper classes are final classes. Immutable class is also final because we need to prevent the subclass to change the state of the parent class.
Example:
final class Parent { }
#HappyCoding
Top comments (0)