How to use final keyword in java properly

The final keyword in Java is used to restrict users. The final keyword in java can be used in many contexts: with variables, with methods and with classes.

The final keyword in java can be applied to variables, a final variable that has no value is called an empty final variable or the final variable is not initialized. It can only be initialized in Constructor. The final empty variable can also be static, which will only be initialized in the static block.

The final variable in Java

If you make any variables final, you can not change the value of the final variable (it will be a constant).

Example of the final variable in Java

Assuming there is a final variable called speedlimit, we are changing the value of this variable, but it can not be changed because once the final variable has been assigned the value is never changed.

final-keyword-in-java

The final method in Java

If you make any method final, you can not override it.

Example of the final method in java


final-keyword-in-java

The final class in Java

If you create any class that is final, you can not inherit it.

final-keyword-in-java
Question: Is the final method inherited?
Yes, the final method is inherited but you can not override it. For example:
final-keyword-in-java
Question: What is a final empty or uninitialized variable?
A final variable that is not initialized at the time of declaration is called the final variable. If you want to create a variable that is initialized at the time the object was created and once it has been initialized, it can not be changed, the final empty variable is useful in this case. For example, the PAN CARD number of an employee.

It can only be initialized in Constructor. Here is an example of the final empty variable:
final-keyword-in-java
Question: Can we initialize an empty final variable?
Yes, but only in Constructor. For example:
final-keyword-in-java

The static final variable is empty in Java

A static final variable that is not initialized at the time of declaration is a static final variable. It can only be initialized in the static block.

Here is an example of an empty static final variable in Java:
final-keyword-in-java
Question: What is the final parameter?
If you declare any parameter as final, then you can not change its value.
final-keyword-in-java
Running the above program will give Compile Time Error.

Question: Can we declare a final constructor?

No, because the constructor is never inherited.

To find out more about static keyword in java:

Comments