All Courses
Final Keywords in Java

Final keyword in Java

April 30th, 2019 Java

Final keyword in Java

Keyword – ‘final’ can be used while declaring variables, methods and classes.

Final keyword with variable:

The variable which is defined as final becomes constant. changing the value of this variable  is not possible and remains constant and unchangeable even though it is a variable.

Example : final int i = 10;

The value of i is 10 when we try to change the value of i variable we will get a compile time error.

If we try to reassign the value of i compile time error is raised.

Compile time error : The final local variable i cannot be assigned.

Final instance variable:

The variable which is inside the class and outside the method is called instance variable. This variable should be initialized at the time of object creation i.e final variable can be initialized at two places i.e either in the constructor or in the instance block.

class FinalExample{
final int i;
final int j;
public FinalExample(){
i = 20;
}
{
j = 30;
}
}

Final local variable:

The variable which is declared inside the method is called Local variable. And it is initialized at the time of declaration.

class FinalLocal{
public void method(){
final int i = 10;
}
}

Final keyword with reference type variable :

when we make the reference variable as final the value may be reassigned but the reference can’t be changed.

Ex: When we make array as final the size will be constant but we can reassign the values in the array.

final int[] ar = {2,3,4,5,6};

In the above example we can change the values of array ‘ar’ but we can’t change the size.

Final keyword with method :

When the method signature has final keyword then the method can’t be overridden in the child class.

class Parent{
public final void method(){
System.out.println(“parent method”);
}
}
class Child extends Parent{
public void method(){
System.out.println(“child method”);
}
}
Compiletime error : Cannot override the final method from Parent

Final keyword with class :

When the class is declared as final inheriting of that class is not possible.

final class Parent{
}
class Child extends Parent{
}
Compilation errors : The type Child cannot subclass the final class Parent as.
Social Share:

0 responses on "Final keyword in Java"

Leave a Message

Your email address will not be published. Required fields are marked *