☰ 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:
class
method
variable(instance, static, local and parameter)
final class
A final class cannot be extended; no class can extend final class.
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.
final method
If a method is declared as final, it cannot be overridden or it stops overriding.
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.
All Chapters