BCA / B.Tech 9 min read

The `final` Keyword in Java

Quick Summary & Key Takeaways

  • • Subject Focus: Java Notes in English (BCA / B.Tech Syllabus)
  • • Core Topic: The `final` Keyword in Java - General Topics
  • • Overview: What is the `final` Keyword in Java? The final keyword is a non-access modifier that can be applied to variables, methods, and classes. It is used to a...
  • • Key Concepts: Java final keyword, Variables methods classes Hindi, Inheritance prevention final,

What is the `final` Keyword in Java?

The final keyword is a non-access modifier that can be applied to variables, methods, and classes. It is used to apply restrictions on these elements, essentially making them unchangeable in some way. Once declared as `final`, an entity cannot be modified, overridden, or inherited.

Applications of the `final` Keyword:
  1. Final Variable (Constant): When a variable is declared as `final`, its value cannot be changed once it has been initialized. It effectively becomes a constant.
    class Circle {
        final double PI = 3.14159; // This value can never be changed.
    
        double calculateArea(double radius) {
            // PI = 3.14; // This would cause a compile-time error.
            return PI * radius * radius;
        }
    }
  2. Final Method (Prevent Overriding): When a method is declared as `final`, it cannot be overridden by a subclass. This is used to enforce a specific implementation and prevent subclasses from altering it.
    class Vehicle {
        final void displayInfo() {
            System.out.println("This is a vehicle.");
        }
    }
    
    class Car extends Vehicle {
        // void displayInfo() { ... } // Compile-time error: Cannot override the final method.
    }
  3. Final Class (Prevent Inheritance): When a class is declared as `final`, it cannot be extended or inherited by any other class. This is often done for security and immutability, as seen in core Java classes like `String` and `Integer`.
    final class SecureData {
        // ... class members
    }
    
    // class ExtendedSecureData extends SecureData { ... } // Compile-time error: Cannot inherit from final class.

Frequently Asked Questions (FAQs)

What is the `final` Keyword in Java?.
Understanding The `final` Keyword in Java is fundamental to mastering Java Notes in English. It covers crucial concepts, solved problems, and revision points essential for academic and entrance exam success.
You can read free solved examples, detailed explanations, and key formulas for The `final` Keyword in Java directly on the NotesMedia website or by downloading the NotesMedia App.