Final keyword in Inheritance

In Java, the final keyword plays an important role in controlling inheritance and method overriding. Here's a detailed explanation.


🔐 final Keyword in Inheritance

The final keyword can be applied to:

UsagePurpose
final class                    Prevents a class from being subclassed
final method                    Prevents a method from being overridden
final variable                    Prevents a variable from being reassigned
When applied in the context of inheritance, final helps to restrict changes to a class or method.

📌 1. final Class

A final class cannot be extended. You use it when you want to stop inheritance completely.

✅ Example:

final class Vehicle {
void start() { System.out.println("Vehicle starting"); } } // ❌ This will give a compile-time error class Car extends Vehicle { // Error: cannot inherit from final class }

📌 2. final Method

A final method cannot be overridden in any subclass. You use it when you want to prevent overriding, for example, for security or consistency.

✅ Example:


class Vehicle { final void start() { System.out.println("Vehicle starting"); } } class Car extends Vehicle { // ❌ Compile-time error // void start() { // System.out.println("Car starting"); // } }

🧠 Use Cases:

  • Prevent overriding of sensitive logic

  • Prevent subclass from changing inherited behavior


🧠 Why Use final in Inheritance?

  • Security: Prevent altering critical methods

  • Optimization: Java compiler may optimize calls to final methods

  • Design Integrity: Enforce that some classes/methods remain unchanged


❌ What You Cannot Do with final in Inheritance

Action    Allowed?Reason
Extend a final class                Final class is sealed
Override a final method                    Final methods are locked
Modify a final variable                Final variables are constants

✅ Summary

final Applied ToEffect in Inheritance
Class                Cannot be extended
Method                Cannot be overridden
Variable                Not related to inheritance, but value-fixed

Comments

Popular posts from this blog

Object Oriented Programming PBCST304 KTU BTech CS Semester 3 2024 Scheme - Dr Binu V P

Introduction to Java Programming

Inheritance and Polymorphism