Can a Final Class be Subclassed in Java



In Java Inheritance is a fundamental feature that allows a class to derive properties and behaviors from another class. In Java, not all classes can be subclassed. A final class is a special type of class that cannot be extended. 

What is a Final Class in Java?

In Java, a class is declared final using the final keyword. The final modifier for finalizing the implementations of classes, methods, and variables.

When a class is marked as final, it means ?

  • It cannot be extended.
  • All its methods remain unchanged in their original form.

Declaring a Final Class ?

final class FinalClass {
    void display() {
        System.out.println("This is a final class.");
    }
}

Can a Final Class Be Subclassed?

The main purpose of using a class being declared as final is to prevent the class from being subclassed. If a class is marked as final then no class can inherit any feature from the final class.

You cannot extend a final class. If you try it gives you a compile time error.

Java prevents the subclassing of a final class to maintain its integrity and avoid modifications through inheritance.

Example

Below is an example of subclassing the final class ?

final class Super {
   private int data = 30;
}
public class Sub extends Super{
}

Output

C:\Sample>javac Sub.java
Sub.java:7: error: cannot inherit from final Super
public class Sub extends Super{
                         ^
1 error

Conclusion

A final class cannot be subclassed in Java because it prevents inheritance. This restriction helps maintain the integrity of the class, improves performance, and ensures security, making it ideal for immutable and utility classes.

Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2025-02-27T19:28:35+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements