The final keyword in Java

Beknazar
3 min readApr 14, 2021

--

The final keyword can be used with variables, methods, and classes.

The final keyword is a special specifier that you can put together with variable, method, and class declarations.

  1. Final variable.
  2. Final method.
  3. Final class.

Final variable

Let’s start with the variables. Once we assigned a value for the final variable there is no way we can reassign it.

DOES NOT COMPILE
  • Once a value is assigned we cannot change it.
  • We use the final variable as constants in our code.
  • static final is a common approach to create constant values in Java.
DOES NOT COMPILE
  • final keyword can be used with local variables as well. The idea is the same cannot change the value.
DOES NOT COMPILE
  • can be used with method arguments. Again cannot reassign the value of an argument.

Final method

If we declare our method as final, no child class can override it. Basically, we cannot override final methods.

Main2.java DOES NOT COMPILE
  • In the above example, we tried to override the final method and we are getting a compilation error.

Final class

if we declare our class as final, we cannot extend it. For example java.lang.String class is final and we cannot extend it.

Main2.java DOES NOT COMPILE

That’s all I have for the final keyword in Java.

--

--