Loading

Final Keyword 


 The final keyword can be used in all below levels:

  • variable
  • method
  • class  

1. Final variable:- Once we declare a variable as a final we can't re-assign the value of the variable.

Syntax:

final data_type variable_name=value;

Example: 

package quipohouse;
class FinalVariable {
	public static void main(String[] args) {

		final int X = 5;
		      X=10;           //gives error as re-assignment is not permitted
		System.out.println(X);
	}
}

Output: 

5

2. Final method:- Whenever we declare a method as a final our extended or inherited class can't override it.

Syntax:

 class Class_Name{
 final return_type method_name(){
     // code
 }
 }

Example:

package quipohouse;
class A {
	final void finalMethod() {
		System.out.println("Inside Final Method");
	}
}
class B extends A {
       // method overriding
	final void finalMethod() {        // gives compilation error as it cannot be overriden
		System.out.println("Inside Final Method");
	}
	public static void main(String[] args) {
		B b = new B();
		b.finalMethod();
	}
}

Output:

Error: LinkageError occurred while loading main class B
	java.lang.IncompatibleClassChangeError: class B overrides final method A.finalMethod()V

 3. Final class:-  Whenever we declare a class as a final it can't be extended or inherited to sub-classes.

Syntax:

final class Class_Name
{
   //code
}

Example:

package quipohouse;
final class A {
}
class B extends A {      
 //gives error as final classes cant be extended
	public static void main(String[] args) {
	}
}

Output:

The type B cannot subclass the final class A