The final keyword in Java

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

Photo by Maxim Zhgulev on Unsplash

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.

Software Developer, Java Instructor https://www.techleadacademy.io/