In this tutorial, we will learn about the final keyword in Java. The final keyword is a non-access modifier which can be used with variable, method and classes. It makes the value of those unchangeable.
The final keyword is used to stop value change, overriding and inheritance. It is useful when we want to store the value without changing, for example PI (3.1415..). Now let’s see how the final keyword is used with variables, methods and classes.
1) final keyword with a Variable
Once the variable has declared as final, the value of it cannot be changed through the program or a code. In the below example, we are going to change the value of age,but it can’t be changed because it has declared as final.
class Person { final int age=20; //final variable void run() { age=30; } public static void main(String[] args) { Person p=new Person(); p.run(); } }
Output: Compile Time Error
2)final keyword with a Method
If we make any method as final, we cannot override that method throughout a code. In the below example the method eat() is declared as final, hence the method eat() in Dog cannot override eat() in Animal.
class Animal { final void eat() { System.out.println("This is Parent class method."); } } class Dog extends Animal { void eat() { System.out.println("This is child class method."); } public static void main(String[] args) { Dog obj=new Dog(); obj.eat(); } }
Output: Compile Time Error
3)final keyword with a Class
If we make any class as final, we cannot extend it that means inheritance is not possible. In the below example Bird is declared as final, hence it cannot be extended.
final class Bird {} class Parrot extends Bird { void eat() { System.out.println("Parrot is eating."); } public static void main(String[] args) { Parrot p=new Parrot(); p.eat(); } }
Output: Compile Time Error