In the Java programming language, the final keyword is used in several contexts to define an entity that can only be assigned once. Once a final variable has been assigned, it always contains the same value.
But here we are discussing about final method in java. If you declare any method in java with the keyword then that the method cannot be overridden by sub-classes.
You might wish to make a method final if it has an implementation that should not be changed and it is critical to the consistent state of the object.
For example, you might want to make the getFirstPlayer
method in this ChessGame
class final:
class ChessGame { enum ChessPlayer { WHITE, BLACK } ... final ChessPlayer getFirstPlayer() { return ChessPlayer.WHITE; } ... }
The main intention of making a method final would be that the content of the method should not be changed by any outsider.
Methods called from constructors should generally be declared final. If a constructor calls a non-final method, a subclass may redefine that method with surprising or undesirable results.
- If we use final keyword with class name then can’t be inherited.
- If we use final keyword with function then it can be overload
- If you declare any method in java with the keyword then that the method cannot be overridden.