final keyword in java

Posted in Java Inheritance By Raj On December 2, 2017

 

The final is something like a constant, If you don’t want to change any variable once it is declared then we can use final keyword, once you declared a variable with final keyword then you can not change it and you must initialize it otherwise you will get compile time error 

The below things you need to consider before using final keyword

  • if you declare any variable with final keyword then you cannot change the value of it
  • if you declare any class with final keyword then you cannot extend it
  • if you declare any method with final keyword then you cannot override it

Declare final variables

It is a good practice to represent final variables with capital case, if you try to change final variables then you will get compile time error

Initialize final variables

If a final variable is not initialized then you need to use constructor to initialize a final variable, all static final variables must be initialized in static block only

Declare a final class

The final classes cannot be extended, if you try to extend final class then you will get compile time error, please check below codebase

Declare a final method

The methods which are defined in parent class with Final keywords cannot be overridden, if you try to override final methods in the child class then we will get compile time error

If you see the above code the applyBrake method is declared with final keyword, and I am trying to override it using eclipse method override wizard but I don’t see applyBrake method 

java-final-methods