What is Final keyword in Java
Keyword final is used along with:
- Variables
- Methods
- Classes
Final variables:
If you use a variable as a final then the value of variable is become constant. You cannot change the value of a final variable once it is initialized.
e.g.
class Apple{
final int quantity=10; // quantity as a final variable
void show(){
quantity=50;
}
public static void main(String args[]){
Apple ap=new Apple ();
ap.show();
}
}
Output
Apple.java:4: error: cannot assign a value to final variable quantity
quantity=50;
^
1 error
So when you use final variable then you cannot change its value.

Final Method:
Final method cannot be overridden. That means a subclass can call a final method of parent class without any issues but it cannot override it.
e.g.
class Fruit{
final void show(){ // final method
System.out.println("Fruit class created");
}
}
class Apple extends Fruit{
void show(){
System.out.println("Apple class created");
}
public static void main(String args[]){
Apple ap = new Apple();
ap.show();
}
}
Output :
Apple.java:8: error: show() in Apple cannot override show() in Fruit
void show(){
^
overridden method is final
1 error
It will show error because method show is final so it cannot be overridden.
final Class:
If you make class as final then you cannot inherit that class that means you cannot extend it.
e.g.
final class Fruit{
……..
}
class Apple extends Fruit{
void show(){
System.out.println("Apple class created");
}
public static void main(String args[]){
Apple ap = new Apple();
ap.show();
}
}
Output
Apple.java:5: error: cannot inherit from final Fruit
public class Apple extends Fruit{
^
1 error
It will show error because class Fruit is final so it cannot be inherited.
Learn more about Cross-Platform Mobile Technology for Android and iOS using Java in this insightful blog now!