Final Keyword In Java:
The final keyword in java is used to restrict the user. The java final keyword can be used
in many context. Final can be:
variable
method
class
1) Java final variable
If you make any variable as final, you cannot change the value of final variable(It will be
constant).
Syntax: final datatype variable_name = value;
Example : final double pi = 3.142;
Program:
class FinalVariable {
public static void main(String[] args) {
final double pi = 3.142;
[Link]("pi value is :"+pi);
pi =5.43;
[Link]("pi value is :"+pi);
}
}
error:
[Link]: error: cannot assign a value to final variable pi
pi =5.43;
2) Java final method
If you make any method as final, you cannot override it.
Syntax: final returntype methodName(parameters list)
Example: final void display()
Program:
class A
{
final void display()
{
[Link]("This is display() method in A class ");
}
}
class B extends A
{
void display()
{
[Link]("This is display() method in A class ");
}
}
class FinalMethod
{
public static void main(String[] args)
{
B obj = new B();
[Link]();
}
}
error: display() in B cannot override display() in A
void display()
^
overridden method is final
3) Java final class
If you make any class as final, you cannot extend it.
Syntax: final class ClassName
Example: final class Demo
Program
final class A
{
void display()
{
[Link]("This is display() method in A class ");
}
}
class B extends A
{
void display()
{
[Link]("This is display() method in A class ");
}
}
class FinalClass
{
public static void main(String[] args)
{
B obj = new B();
[Link]();
}
}
error: cannot inherit from final A
class B extends A