Final keyword in java

  • Final is a Keyword.

  • You can not change value of a final variable (it is a constant).

  • Java class which declared as Final cannot be extended(Restricting inheritance).

  • A Method declared as final cannot be overridden.

final keyword can be use in three scenario.
  • Final keyword with variables - means that variable become constant that is no one can change the value of variable.
    Example - final int num=10;

  • Final keyword with methods - means that method will not be overridden by other class.
    Example - fianl void print(){}

  • Final keyword with classes - means that class will not inherit by other class.
    Example - final class Demo{}
Note - String class is a final class that is you cannot inherit it.

Final Variable:-

  • Java uses the "final" modifier to declare constants.

  • The "const" modifier will be applicable only to non-primitive types. The primitive types should continue to use the modifier "final".
Example :
public class Final1 {
final int var=10;
     
void display()
 {
	 var=15;
 }
	public static void main(String[] args) {
Final1 f=new Final1();
System.out.println(" final var Cannot be modify");
f.display();

	}

}
Output :

final var Cannot be modify
Exception in thread "main" java.lang.Error: Unresolved compilation problem

Final Method :

Note : Method cannot be overridden.

class Final1 {
	final void display()
	{
		System.out.println("Display Final Method");
	}
	
}
class Final2 extends Final1
{
	 void display()
	{
		System.out.println("Display Final Method");
	}
	public static void main(String args[]) {
		Final2 f= new Final2();
		System.out.println("Displaying Error");
		f.display();
		
	}
}
Output :

Compile Time Error

Final Class :

Note : Java class which declared as Final cannot be extended.
Example :
final class Final1
{
	
}
class Final2 extends Final1
{
	void display()
	{
	 System.out.println(" Final Class");
	}
	public static void main(String[] args) {
		Final2 f=new Final2();
		f.display();
	}
}
Output :

Compile Time Error