×
☰ See All Chapters

final keyword in Java

Once a java class member is made final it cannot be modified further. final keyword can be used at different levels as listed below:

    1. class 

    2. method 

    3. variable(instance, static, local and parameter) 

final class

A final class cannot be extended; no class can extend final class.

java-final-keyword-0
 

final variable

If variable is declared as final then that variable may only be assigned a value only once and cannot be modified or reinitialized later. A final variable must be initialized before its first usage. A final variable will not have a default value. Once final variable is initialized then that variable will become constant. If final variable is made static then that variable must be initialized while declaring it. It is not possible to declare at one place and initialize at other place. If the final variable is a reference variable then it cannot refer to other object but values in the object can be modified.

java-final-keyword-1
 

final method

If a method is declared as final, it cannot be overridden or it stops overriding.

java-final-keyword-2
 

Properties of final members

How to make the class immutable?

Make the class final. A final class cannot be extended by any other class.

When a method is made final what happens?

Method cannot be overridden but can be overloaded.

When a variable is made final what happens?

Once a final variable is initialized it cannot be modified again.

How to initialize static final variable?

static final variable should be initialized in a single statement, declaration and initialization cannot be done in separate lines/statements.

Can we override final methods?

We cannot override final methods. If we try to write the method with same name as in super class final methods we will get compilation error.

java-final-keyword-3
 

All Chapters
Author