The final keyword in Java

  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.

  • 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.
  • final keyword can be used with local variables as well. The idea is the same cannot change the value.
  • 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. 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. DOES NOT COMPILE



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store