The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be:
- variable
- method
- class
The final keyword can be applied with the variables, a final variable that have no value it is called blank final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be static also which will be initialized in the static block only. We will have detailed learning of these. Let’s first learn the basics of final keyword.
1) Java final variable
If you make any variable as final, you cannot change the value of final variable(It will be constant).
Example of final variable
There is a final variable speedlimit, we are going to change the value of this variable, but It can’t be changed because final variable once assigned a value can never be changed.
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
2. Java final Method
In Java, the final
method cannot be overridden by the child class. For example,
class FinalDemo {
// create a final method
public final void display() {
System.out.println("This is a final method.");
}
}
class Main extends FinalDemo {
// try to override final method
public final void display() {
System.out.println("The final method is overridden.");
}
public static void main(String[] args) {
Main obj = new Main();
obj.display();
}
}
In the above example, we have created a final method named display()
inside the FinalDemo
class. Here, the Main class inherits the FinalDemo class.
We have tried to override the final method in the Main class. When we run the program, we will get a compilation error with the following message.
display() in Main cannot override display() in FinalDemo
public final void display() {
^
overridden method is final
3. Java final Class
In Java, the final class cannot be inherited by another class. For example,
final class FinalClass {
// create a final method
public void display() {
System.out.println("This is a final method.");
}
}
class Main extends FinalClass {
// try to override final method
public void display() {
System.out.println("The final method is overridden.");
}
public static void main(String[] args) {
Main obj = new Main();
obj.display();
}
}
In the above example, we have created a final class named FinalClass. Here, we have tried to inherit the final class by the Main class.
When we run the program, we will get a compilation error with the following message.
cannot inherit from final FinalClass
class Main extends FinalClass {