๐ŸŽ‰ Special Offer !    Code: GET300OFF    Flat โ‚น300 OFF on every Java Course
Grab Deal ๐Ÿš€

"final" Keyword in Java  


Introduction
  • final keyword is is a non-access modifier in Java.
  • It is used to restrict modification of variables, methods and classes.
  • If we use final keyword with:
    • Vairable, then its value cannot be changed once initialized.
    • Method, then it cannot be overridden by subclasses.
    • Class, then it cannot be subclassed or extended.

1. "final" Variable:
  • A final variable's value cannot be changed once it is assigned.
  • It must be initialized either at the time of declaration or in the constructor.
  • "final" variables are commonly used to define constants.
  • Java Program Example:
    public class FinalDemo
    {
        public static void main(String[] args)
        {
            final int MAX_MARKS = 100;  // final variable (constant)
            System.out.println("Maximum marks allowed: " + MAX_MARKS);
    
            //MAX_MARKS = MAX_MARKS + 50;     //error as we cannot change the final variable value
        }
    }

2. "final" Method:
  • A final method cannot be overridden by subclasses.
  • This is useful when we want to stop other classes from changing the code inside the method.
  • Java Program Example:
    class Parent
    {
        final void showMessage()
        {
            System.out.println("This is a final method from the Parent class.");
        }
    }
    
    class Child extends Parent
    {
        // Trying to override the final method will cause a compile-time error
        /*
        void showMessage()
        {
            System.out.println("Trying to override.");
        }
        */
    }
    
    public class FinalDemo
    {
        public static void main(String[] args)
        {
            Child obj = new Child();
            obj.showMessage();
        }
    }

3. "final" Class:
  • A final class cannot be extended (i.e., no class can inherit it).
  • This is useful for security and immutability (like the String class).
  • Java Program Example:
    // Final class - cannot be extended
    final class A
    {
        void mA()
        {
            System.out.println("This is class A.");
        }
    }
    
    // Trying to extend a final class will cause a compile-time error
    /*
    class B extends A
    {
    
    }
    */
    
    public class FinalDemo
    {
        public static void main(String[] args)
        {
            A obj = new A();
            obj.mA();
        }
    }