In this article, you’ll learn about Final method in Java with example.
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.
Important Points
- When a method is declared with the final keyword, it is called a final method in java. We cannot override the final method in java.
- If we try to override the final method in java, we get a compilation error because if we are declaring any method with the final keyword, we are indicating the JVM to provide some special attention and make sure no one can override it.
- The methods that are required to follow the same implementation throughout all the derived classes must be declared as a final method.
- We define a final method in java to restrict the unwanted and improper use of method definition by the child class(es) while overriding the final method.