Final keyword and its uses in Java

The final keyword in java used in different contexts. It can be used to do following.

Usages of final keyword

  1. To create constant by making variable final.
  2. To prevent method overriding by making method final.
  3. To prevent inheritance by making final class.

Java Final Variable

As you know sometimes we need to constant value through the program which does not get change. Like while you working circle you need PI which has fixed value 3.14. In this case you can define it as final variable.

We cannot change the value of final variable if already assigned.

Blank Final Variable

A blank final variable is variable which is not initialized during declaration. You should assign value before creating object. You can create either instance property or class level property and need to assign value by following ways.

  1. Instance Blank Final Variable : Using constructor or initializer block.
  2. Static Blank Final Variable : Using static block.

Example 1 Instance Final Variable

This kind of final variable is defined without static keyword. We can assign instance final variable value in constructor or initializer block. While you declared final variable without value then it is said to be blank final variable which need to assign using constructor or initializer block otherwise compile time error will be given.

package com.startwithjava;
public class FinalClassTest {
public final int x; //blank final variable
public final int y=20;
static {
x=10;
}
public static void main(String[] args) {
System.out.println("X="+x);
System.out.println("Y="+y);
}

}

Example 2 Static Final Variable

This kind of final variable is declared using static keyword and all the objects of the class will share it as it associated with class.

We can assign value either during declaration or by using static block.


public class FinalClassTest {
public static final int x; //blank final variable
static {
x=10;
}
public static void main(String[] args) {
System.out.println("X="+x);
}

}

 

Java Final Method

Method overriding is the feature where you can override the parent class method definition in child class. The final keyword can be used to stop method overriding means method defined in parent class cannot be overridden in their child classes.


accessmodifier final returnType methodName(Arguments){

}

Example of Java Final Method


class A{
public final void display(){
System.out.println("A is displaying");
}
}

Java Final Class

By making class final stops the inheritance means no child class can be created for final class. All the wrapper classes are final class.

Example of Java Final Class


package com.startwithjava;

final class Test{
Test(){
System.out.println("Final Test Class");
}
public void display(){
System.out.println("Display invoked");
}
}
public class FinalClassTest {
public static void main(String[] args) {
new Test().display();
}

}

 

Output


Final Test Class
Display invoked

Leave a Reply