USES:
It restrict the user. "final" keyword In Java can be used with different three contexts in java like variable, method and class. If define an entity which may only be assigned once. Now let's try to understand how to use final keyword in java software development language with practical examples for variable, method and class.
final variable
Once you initialize value to final variable, You can not change it latter on anywhere. It will stay as it is. In bellow given example, WHEELS is final variable and initialized with 2. Then i am trying to change it from 2 to 4 but it is showing me compilation error.
public class FinalKeyword {
final int WHEELS = 2; //final variable initialized.
void bikeWheels() {
WHEELS = 4; //This is not allowed. Shows you compile time error.
}
public static void main(String[] args) {
FinalKeyword fk = new FinalKeyword();
fk.bikeWheels();
}
}
In short, We can not change value of final variable.
final method
If method is declared with final keyword, It is called final method in java software development language. You can not override final methods in sub class. So here final keyword will helps you to restrict method overriding. Example is as bellow. Here COLLEGENAME() is final method in parent class and then i am trying to override it in child class but it is showing me compile time error.
public class College {
final void COLLEGENAME(){ //Method declared as final in parent class
System.out.println("abc");
}
}
public class Department extends College{
void COLLEGENAME(){//It will show compile time error because it will not allow to override final methods.
System.out.println("xyz");
}
public static void main(String args[]){
Department dep= new Department();
dep.COLLEGENAME();
}
}
final class
If class is declared with final keyword then class is final class and any other class can not extend it in java software development language. Here, WILDANIMALS is final class and i am trying to extend it in sub class Cow but it is showing me error.
final class WILDANIMALS {
}
//It will show compile time error as WILDANIMALS is final class. You can not extend it.
public class Cow extends WILDANIMALS{
}
This way we can restrict class extension too using final keyword.
Points to remember about final class
final keyword can be used with variable, method or class to make them final.
Local final variable must be initialized during declaration or inside constructor. Otherwise it will show you an error.
We can not declare constructor as final. VIEW MORE about constructor in java.
By default all variables declared in interface are implicitly final. VIEW MORE about interface in java software development language.
Value of final variable can not be changed.
We can not override final method.
Class can not be extended to final class. VIEW POST on inheritance to know more about class extend.
final variable which is not initialized during declaration is called blank final variable and you must need to initialize it in constructor.