Java final modifier


Final modifier just like constant if the final variable is initialized once that value never is changed. It behaves like a constant.

final variable :

  1. final int a = 10;
    

    Final modifier just like constant if the final variable is initialized once that value never is changed. It behaves like a constant.

  2. final int a;
    a = 10;
    
  3. final int a = 10; //error
    a = 100;
    
Program
public class Main 
{
  public static void main(String[] args) 
  {
   final int a;
   a=100; //right
   final int b=10;
   b=100; //wrong
  }
}


final method

A method with final modifier that mehtod can not override.

Program
class A
{
 public final void Show()
 {
  System.out.println("A class");
 }
}
class B extends A
{
 public void Show()
 {
  System.out.println("A class");
 }
}
public class Main 
{
  public static void main(String[] args) 
  {
   B b1=new B();
   b1.Show();
  }
}


final class

final class can not be inherited. It behaves like sealed class.

Program
final class A
{
 public void Show()
 {
  System.out.println("A class");
 }
}
class B extends A
{
 public void Show()
 {
  System.out.println("A class");
 }
}
public class Main 
{
  public static void main(String[] args) 
  {
   B b1=new B();
   b1.Show();
  }
}