The final keyword is a non-access modifier. In Java, “final” is used as a keyword while declaring a variable or any other entity so that their value can not be modified in the future during the compilation process.
public final void test()
{
//code body
}
public final class Test{
{
//code body
}
If we declare a final keyword before a variable, then the assigned value can never be changed once after initialized.
If we do not initialize the final variable at the time of declaration, it is called a blank final variable.
For initializing the blank variable, we need to create a constructor. Only then the value can be initialized.
class A{
final variable1 = 20;
variable1 = 40; //Gives an error
}
We can modify the object:
A obj = new A();
obj.variable1 = 40 //Modification is allowed
If a parameter defines as final, then its value will not change anywhere in the function.
class CheckParameter(final int x){
x = 4; //attemps to change the variable will cause an error.
}
By making any method final, the method can not be overridden by any other subclass. But we can inherit the final method; there is no restriction with the inheritance of the final method.
class A {
final void FinalFunction(){
System.out.print(“Hello”);
}
}
Trying to override the FinalFunction() will cause an error.
The final class not be extended.
final class A{}
class B extends A{ //error non extendable class
public static void FaultFunction(){
System.out.println(“Executed”);
}
}
Main.java:6: error: cannot assign a value to final variable x
myObj.x = "Website";
|