Final Class in Java

Java, known for its robustness and versatility, offers various ways to control and restrict the behavior of classes and methods. One such feature is the final keyword, which can be applied to classes, methods, and variables. In this tutorial, we’ll focus on the concept of a final class in Java and explore its significance in the world of object-oriented programming.

What is final class in Java?

The final class in Java is a class that cannot be extended or subclassed. It serves as a way to declare a class as complete, meaning that it should not be further modified by creating subclasses. When we mark a class as final, we’re essentially saying, “This class is finished, and no one should be able to inherit from it.”

Key characteristics of final classes

  1. Cannot Be Extended: The primary characteristic of a final class is that it cannot be extended. Any attempt to create a subclass of a final class will result in a compilation error. This is useful when we want to prevent others from altering or extending a specific class’s behavior.
  2. Security and Stability: Final classes are often used in Java libraries to ensure the stability and security of critical classes. By making a class final, library developers can guarantee that its behavior remains consistent across different applications.
  3. Optimization: The Java compiler can apply certain optimizations to final classes, as it knows that no subclasses will alter their behavior. This can lead to performance improvements in some cases.

Example of final class

Let’s consider a simple example to illustrate the concept of a final class:

final class Circle {
    private double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    public double calculateArea() {
        return Math.PI * radius * radius;
    }
}

In this example, the Circle class is marked as final. This means that it cannot be extended by creating subclasses like BigCircle or SmallCircle. It’s a self-contained class with a fixed behavior.

When to use final class in Java?

You might wonder when to use final classes in our Java projects. Following are some scenarios where they can be beneficial:

  1. Immutable Classes: If we want to create immutable classes (classes whose state cannot be changed once initialized), marking them as final is a good practice.
  2. Utility Classes: Classes containing utility methods that should not be extended can be marked as final to prevent unintended modification.
  3. Security and API Stability: In library development, final classes help ensure the stability of APIs and prevent unintended changes.

Some examples of final classes in Java include: