Final keyword in java

Final is a Non-acess modifier.The final keyword in Java can be used for different purposes. Most commonly, it is used to create immutable objects. This means that once an object is created, it cannot be modified. It can also be used to prevent inheritance or to make a class static. In short, the final keyword is a versatile tool that can be used in a variety of ways.

The final keyword can be applied with the variables, a final variable that have no value it is called blank final variable or uninitialized final variable. It can be initialized in the constructor only.

Example

class Main {

public static void main(String[] args) {

// create a final variable

final int CLAPS = 100;

// try to change the final variable

CLAPS = 200;

System.out.println("Claps: " + CLAPS);

}

}

From above e.g if we try to change the value it will give an Output compile time error.

Final Method

class RandomClass {

// create a final method

public final void randomMethod() {

System.out.println("Hello from RandomClass");

}

}

class Main extends RandomClass {

// try to override final method

public final void randomMethod() {

System.out.println("Hello from Main");

}

public static void main(String[] args) {

Main obj = new Main();

obj.randomMethod();

}

}

In above example we tried to overriding the random method which is final method inside a class.

If we try to run above e.g again we will see compile time error.

Final Class

final class FinalClass {

public void randomMethod() {

System.out.println("Hello from FinalClass");

}

}

// try to extend the final class

class Main extends FinalClass {

public void randomMethod() {

System.out.println("Hello from Main");

}

public static void main(String[] args) {

Main obj = new Main();

obj.randomMethod();

}

}

Output

Compile time Error.