final is a Java keyword which is used to restrict the user, the final keyword can be used in variable, method and class.
When the variable is defined as final, you can not change the value of the final variable, so it is constant.
Table of Contents
Usage for Java final keyword
- Stop value change of variable
- Stop Method overriding
- Stop Inheritance
Java final keyword with variable
We assign any variable as final it means youcan not any changes the value of the final variable (it will be constant)
This is the example for usage of final keywordin Java language
program 1
public class FinalDemo
{
public static void main (String args[])
{
final int i; // Final variable
i=5; // This variable assignment can not changed
System.out.println(i);
} // End of method
program 2
public class FinalDemo
{
public static void main (String args[])
{
final int i; //final variable
i=5; //Assign the value to final variable
i++; //can not be change or reassign
System.out.println(i);
}
}
There is a final variable int I; we have already assigned value as 5. We are going to change the value of this variable, but it can’t be changed
final key word use with method
Program 1
This is method overriding program in inheritance. Two methods, Both methods holds the same name. so one method can be overridden another method.
public class FinalDemo1
{
public static void main (String args[])
{
B obj=new B();
obj.show();
}
}
class A
{
public void show()
{
System.out.println(“Show my name karmehavannan”);
}
}
class B extends A
{
public void show()
{
System.out.println(“Show my father name sathasivam”);
}
}
Program 2
This is method overriding program in inheritance. Two methods, Both methods are the same name. But the final keyword used the first method.
So both methods cannot be overridden
public class FinalDemo1
{
public static void main (String args[])
{
B obj=new B();
obj.show();
}
}
class A
{
final public void show() //final keyword is used to this method.So it can not be overridden
{
System.out.println(“Show my name karmehavannan”);
}
}
class B extends A
{
public void show()
{
System.out.println(“Show my father name sathasivam”);
}
}
final key word use with class
if you make any class as final, you cannot extend it.
Program 1
public class FinalDemo1
{
public static void main (String args[])
{
B obj=new B();
obj.show();
}
}
class A
{
public void show()
{
System.out.println(“Show my name karmehavannan”);
}
}
class B extends A
{
public void show()
{
System.out.println(“Show my father name sathasivam”);
}
}
Program 2
public class FinalDemo1
{
public static void main (String args[])
{
B obj=new B();
obj.show();
}
}
final class A // use final key word this class
{
public void show()
{
System.out.println(“Show my name karmehavannan”);
}
}
class B extends A
{
public void show()
{
System.out.println(“Show my father name sathasivam”);
}
}
the final method is inherited but it cannot be override
Final class in Java
Related post
This keyword in Java