Final keyword in Java:
Final is a keyword (or) reserved word in java it is used to restrict the user. We can apply to variables, methods, class. Once we are applied the final keyword to variable’s we can’t change the value of a variable.
The final keyword not applicable to the constructor.
Final methods:
Final keyword also applicable to methods we can make any method as a final method. If a method is declared with final keyword we can’t override that method. The subclass calls the parent class method but we can’t override the method.
We can use final keyword to main() method in java.
Syntax:
class Sample{
final void method_name(){
//
}
}
Program:
class ABC{
final void display(){ //final method
System.out.println(“parent class method”);
}
}
class EFG extends ABC{
void display(){
System.out.println(“child class method”);
}
public static void main(String args[]){
EFG obj = new EFG();
obj.display();
}
}
Final variables:
If we use the final keyword to variables we can’t change the value of a variable. The final variables are initialized value at variable declaration time. We can apply the static keyword to final variables. Mostly final variables are used in interfaces and final variables are constants.
Example:
final int a=100;
Program:
public class Sample{
static final int a=100; //final variable
public final static void main(String []args){
System.out.println("Hello World");
System.out.println("Final variable Is"+a);
}
}
Final class:
If a class declared with final keyword we can’t extend it.
Program:
final class ABC{ } //final class
class EFG extends ABC{
void display(){
System.out.println(“child class method”);
}
public static void main(String args[]){
EFG obj = new EFG();
obj.display();
}
}
Compile time error will occur.
EmoticonEmoticon