Java Made Simple: What is final keyword with Example?

Java Made Simple: What is final keyword with Example?


Java comes with a final keyword that can be applied to variables, classes and methods and in each place when applied gives different meaning.
  1. A final variable cannot be reassigned.
  2. A final method cannot be overridden.
  3. A final class cannot be extended.

Eventhough, final keyword works differently, one common purpose(functionality) we can derive is something cannot be changed or cannot be done.

Let us apply final to the above three entities programmatically one-by-one.

final keyword with Variable: 1. A final variable cannot be reassigned

Java does not support const keyword of C/C++. In its place, in Java, final keyword is used. Once a final variable is given a value, it cannot be changed again. final variable value is fixed.

final keyword with Method: 2. A final method cannot be overridden

Super class methods can be overridden by subclass with its own functionality. That is, subclass uses the same method name of super class and gives different output. This is called "method overriding”, a feature Java supports.

Sometimes, the super class can impose a restriction on subclass saying that its methods (may be one or all) cannot be overridden by subclass. Then, the super class simply adds "final" to its method declaration. By adding final to its method, super class prevents subclass to override. That is, final methods of super class cannot be overridden by subclass. As usual, non-final methods can be overridden at the choice of the subclass.

Let us explain through an example.

Code is well commented.

final keyword with Class: 3. A final class cannot be extended

Sometimes, a class may not be willing to be inherited by other classes. That is, other classes cannot extend. To achieve this, the class simply adds final its class declaration. Explained with an example.

final keyword

final class methods can be used by other classes by composition.

Leave a Reply

Your email address will not be published. Required fields are marked *