Final Class in Java (With Simple Example and Explanation)

Final class in Java example with code and explanation

If you're learning Java, you've likely seen the keyword final. It can be used with variables, methods, and classes. In this article, we’ll focus on final classes in Java and understand how they work using simple examples.

This concept is important for both exams and real-world programming because it helps control inheritance and improves code security.


What is a Final Class in Java?

A final class is a class that cannot be extended or inherited by any other class.

Once a class is declared as final, no other class can subclass it.

Final Class Syntax
final class ClassName {
    // code
}
  

Why Use Final Class?

Final classes are used when you want to restrict inheritance and make your code more secure and stable.

  • Prevents unwanted modification
  • Improves security
  • Ensures consistent behavior
  • Used in core Java classes like String

Example Program of Final Class

Let’s understand this with a simple example.

Final Class Example
final class Animal {
    void display() {
        System.out.println("This is a final class");
    }
}

class Test {
    public static void main(String[] args) {
        Animal obj = new Animal();
        obj.display();
    }
}
  

Output

Program Output
This is a final class
  

Trying to Extend Final Class (Error Example)

If you try to inherit a final class, Java will give a compile-time error.

Invalid Code
final class Animal {}

class Dog extends Animal { // ERROR
}
  

Error: Cannot inherit from final class


Real-World Examples of Final Classes

Some commonly used final classes in Java include:

  • String
  • Math
  • Wrapper classes (Integer, Double)

These classes are made final to prevent changes and maintain consistency.


Final Class vs Final Method vs Final Variable

Feature Final Class Final Method Final Variable
Inheritance Not allowed Allowed but cannot override Not applicable
Modification No subclassing No overriding Value cannot change

Best Practices

  • Use final class when behavior should not change
  • Avoid unnecessary use of final keyword
  • Use final for security-sensitive classes

Common Mistakes

  • Trying to extend final class
  • Confusing final class with abstract class
  • Overusing final unnecessarily

FAQ

What is a final class in Java?

A class that cannot be inherited by other classes.

Can we extend a final class?

No, it will cause a compile-time error.

Why is String class final?

To ensure immutability and security.


Conclusion

Final classes are an important part of Java programming. They help protect your code from unwanted changes and ensure stability. Understanding when and how to use them will improve your coding skills and help you write better applications.


📚 Read More

Comments