final
keyword can be used on a local variable, member variable, static variable, method or a class. Shown below are the implications of
final
keyword being applied at various levels.
- Local variable: If a variable is declared with the keyword
final
, then the value can not be changed after initialization. Here the variable pi
is declared and initialized to 3.14
, if we want to change it 3.45
, then it causes a compilation error.
final double pi = 3.14;
pi = 3.45; // Causes a compilation error
- Member variable: If a member variable of a class is marked as
final
, then it has to be initialized while it is declared or initialized in the constructor. Otherwise it causes a compilation error. Here the initializations in class A
and B
are correct, where as for class C
, it is a problem since the variable j
is neither initialized when declared nor initialized in the constructor.
class A
{
final int i = 10;
}
class B
{
final int k;
B(int k)
{
this.k = k;
}
}
class C
{
final int j; // Causes a compilation error
C()
{
}
}
- Class or
static
variable: If a static variable of a class is marked as final
, then it has to be initialized while it is declared or initialized in the static block. Otherwise it causes a compilation error. Here the initializations in class M
and N
are correct, where as for class O
, it is a problem since the variable j
is neither initialized when declared nor initialized in the static block.
class M
{
static final int i = 10;
}
class N
{
static final int k;
static
{
k = 4 * 20;
}
}
class O
{
static final int j; // Causes a compilation error
}
- Method: If a method of a class is marked as
final
, then it can not be overridden in any of its sub-classes. It causes a compilation error, if we try to override a final
method.
class X
{
final void print()
{
System.out.println("This method can not be overridden.");
}
}
class Y extends X
{
void print() // Causes a compilation error, can not override a final method
{
}
}
- Class: If a class itself is marked as
final
, then it can not be inherited (or extended). It causes a compilation error, if we try to extend a final
class. Here class P
is marked as final
, hence it can not be inherited.
When you use
final
modifier for
class
, it means
- Class is fully implemented and there should not be any sub-class of this class.
- Modifier
final
is totally opposite of abstract
modifier. Hence for a class, final
and abstract
modifier cannot be used together.
final class P
{
}
class Q extends P
{
// Causes a compilation error, can not inherit a final class
}