final keyword in Java
final keyword is used for making a variables, method or a class final to avoid from modifying the data or values which are once defined.
final variables
final keyword when used in variables prevents the variable from re-intialization or modification of the stored value.
Variable declaration pre-fixed with the final keyword is the way of representing a variable as final.
Example
class FinalVariableTest{
final int num=10;
public static void main(String args[]){
FinalVariableTest fvt=new FinalVariableTest();
fvt.num=15;
}
}
Output
error: cannot assign a value to final variable num
If final variable is declared but not assigned any value, the value can be assigned only in constructor and assigning in any other methods are not allowed.
Example 1
class FinalVariableTest1{
final int num;
FinalVariableTest1(){
num=10;
}
public static void main(String args[]){
FinalVariableTest1 fvt=new FinalVariableTest1();
System.out.println("Number "+fvt.num+" is assigned in constructor");
}
}
Output
Number 10 is assigned in constructor
Example 2
class FinalVariableTest2{
final int num;
void initcheck(){
num=10;
}
public static void main(String args[]){
FinalVariableTest2 fvt=new FinalVariableTest2();
fvt.initcheck();
}
}
Output
error: cannot assign a value to final variable num
It the final variable is static, variables can also be initialized in a static block of class.
Example
class FinalVariableTest{
static final int num;
static{
num=15;
}
public static void main(String args[]){
FinalVariableTest fvt=new FinalVariableTest();
System.out.println("Number "+fvt.num+" is assigned in static block");
}
}
Output
Number 10 is assigned in static block
final methods
To prevent a method of class from overriding in another class, we can use final keyword in method.
Method definition pre-fixed with the final keyword is the way of representing a method as final.
Example
class Pegion{
final void fly(){
System.out.println("Pegions can fly.");
}
}
class Dog extends Pegion{
void fly(){
System.out.println("Dogs cannot fly.");
}
}
class FinalMethodTest{
public static void main(String args[]){
Dog dg=new Dog();
dg.bark();
}
}
Output
error: fly() in Dog cannot override fly() in Pegion
final class
To prevent a class from inherited or implemented by another class, we can use final keyword in class.
class definition pre-fixed with the final keyword is the way of representing a class as final.
Example
final class Bicycle{
void run(){
System.out.println("Bicycle is running");
}
}
class Television extends Bicycle{
void turnon(){
System.out.println("Television is turned on");
}
}
class FinalClassTest{
public static void main(String args[]){
Television vu=new Television();
}
}
Output
error: cannot inherit from final Bicycle