TeachingBee

Final Class In Java

final class in java

Final class in Java prevent inheritance and provide immutability guarantees. In this article, we will learn:

  • What is a final class and how to declare one?
  • Properties of final class in java
  • When to use final classes
  • What happens when we try to inherit from a final class
  • Some Predefined final classes in Java
  • Advantages of using final classes

What is Final Class in Java?


In Java programming, a final class is a class that cannot be extended (subclassed or inherited from). In other words, no other class can inherit from a final class. This is achieved by using the keyword final in the class declaration.

The primary purpose of a final class in java is to prevent inheritance. If a class is declared as final, no other class can extend it.They are often used in conjunction with immutability. By making a class final and its fields private and final, you can ensure that the class’s state cannot be altered once it has been created. This is particularly useful for creating immutable objects.

Properties of Final Class In Java

Some key properties of final classes in Java:

  • A final class cannot be subclassed. Attempting to extend a final class will result in a compile-time error. This prevents other classes from inheriting from and modifying the behavior of a final class.
  • All the methods in a final class are implicitly final. You do not need to actually declare them as final. Since the class cannot be subclassed, there is no way for a subclass to override the methods.
  • Instance fields and static fields in a final class can be modified, unless they are declared as final themselves. The final modifier on a class only prevents subclassing, not modification of fields.
  • A final class can extend other classes and implement interfaces like any other non-final class. The final modifier only prevents other classes from extending this class.
  • Final classes are useful for classes that need to remain immutable for security or thread-safety purposes. Examples from the Java API include the String class and Box classes like Integer and Long.

So, final keyword prevents subclassing, implicitly finalizes all methods, but allows fields to be modified unless themselves declared final. Finality allows immutability but does not prevent extending other classes.

Creating Final Class In Java

To create a final class in Java, you simply add the final modifier to the class declaration. For example:

public final class FinalClass {

  // class contents

}

Adding final prevents the class from being subclassed. So you cannot extend FinalClass in this example.

When To Use Final Class In Java

You should use a final class in Java when you want to prevent that class from being subclassed or extended. Here are some common scenarios and Java code examples where using a final class is appropriate:

Utility Classes

When you have a class that contains only static methods and is used as a utility, making it final ensures it cannot be extended or modified.

final class MathUtils {

    private MathUtils() {} // Private constructor to prevent instantiation

    public static int add(int a, int b) {
        return a + b;
    }

    public static int multiply(int a, int b) {
        return a * b;
    }
}

By making MathUtils final, you ensure that it cannot be subclassed or modified. Users can only use its static methods.

Immutable Classes

In cases where you want to create immutable objects, you can make the class final to prevent any modification to its state once it’s constructed.

final class ImmutablePerson {
    private final String name;
    private final int age;

    public ImmutablePerson(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

This ImmutablePerson class ensures that once an instance is created, its state cannot be changed.

Security Concerns

In cases where you want to protect sensitive data or operations, making a class final can enhance security.

final class SecureDataStorage {
    private final String encryptedData;

    public SecureDataStorage(String encryptedData) {
        this.encryptedData = encryptedData;
    }

    // Additional security-related methods
}

By making SecureDataStorage final, you prevent any unauthorised changes to the data it holds.

Singleton Design Pattern

When implementing the Singleton design pattern, you can make the Singleton class final to ensure there’s only one instance.

final class Singleton {
    private static final Singleton INSTANCE = new Singleton();

    private Singleton() {} // Private constructor

    public static Singleton getInstance() {
        return INSTANCE;
    }

    // Other methods and data
}

The final keyword guarantees that there won’t be subclasses or multiple instances of the Singleton.

In all these cases, using the final keyword ensures that the class cannot be extended, which aligns with the design intent and enhances code stability and security.

Trying to Inherit from Final Class In Java

In Java, you cannot inherit or extend from a final class. When a class is declared as final, it means that it is intended to be a terminal or endpoint class, and no other class can extend it. Attempting to create a subclass of a final class will result in a compilation error.

Here’s an example to illustrate this:

final class FinalClass {
    // Class members and methods
}

class Subclass extends FinalClass { // This will result in a compilation error
    // Subclass members and methods
}

public class Main {
    public static void main(String[] args) {
        // Code here
    }
}

In the code above, the FinalClass is declared as final, indicating that it cannot be extended. If you attempt to create a subclass Subclass that extends FinalClass, you will get a compilation error.

The error message will typically be something like:

error: cannot inherit from final FinalClass
class Subclass extends FinalClass {
                        ^

Predefined Final Classes in Java

In Java, there are several predefined final classes provided by the Java Standard Library and the Java API. These classes are marked as final by design, and they serve various purposes in the Java ecosystem. Here are some examples of predefined final class in Java:

Class NameDescription
java.lang.StringRepresents a sequence of characters, and it’s immutable and widely used for text handling.
java.lang.MathProvides mathematical functions and constants as static methods.
java.lang.SystemOffers access to system resources and standard input/output streams.
java.lang.IntegerWrapper class for the int primitive data type.
java.lang.DoubleWrapper class for the double primitive data type.
java.lang.BooleanWrapper class for the boolean primitive data type.
java.util.CollectionsContains utility methods for working with collections like lists, sets, and maps.
java.util.ArraysProvides utility methods for working with arrays.
java.lang.EnumBase class for all enumeration types in Java.
java.time.LocalDateRepresents a date without a time zone.
java.time.LocalDateTimeRepresents a date and time without a time zone.
java.time.ZonedDateTimeRepresents a date and time with a time zone.
Predefined Final Classes in Java

Advantages Of Final Class In Java

The advantages of using final class in Java are:

  • Enhances Security and Integrity: Final classes cannot be extended, ensuring consistent and secure behavior.
  • Ensures Thread Safety: Immutable final classes guarantee thread safety by preventing state changes.
  • Optimizes Performance: Final classes allow for performance optimizations due to their predictable behavior.
  • Clarifies Design Intent: Marking a class as final communicates the intent to discourage unnecessary subclassing.
  • Promotes Consistency: Final classes provide a stable foundation, reducing the risk of unexpected changes.

Key Takeaways

  • Final class in java cannot be subclassed or inherited from. The final keyword prevents extension.
  • All methods in a final class are implicitly final and cannot be overridden.
  • Fields can be modified unless explicitly declared final. Only subclassing is prevented.
  • Final classes are useful for immutability, thread-safety, security and performance.
  • Predefined final classes in Java include String, Integer, System, Collections etc.
  • Key advantages of final classes are enhanced security, thread-safety, performance and clearer design intent.

Also read,

Checkout more Java Tutorials here.

I hope You liked the post 👍. For more such posts, 📫 subscribe to our newsletter. Try out our free resume checker service where our Industry Experts will help you by providing resume score based on the key criteria that recruiters and hiring managers are looking for.

FAQ

Can final class be instantiated in Java?

What is final object in Java?

What is the difference between final and static in Java?

Is StringBuilder a final class in Java?

90% of Tech Recruiters Judge This In Seconds! 👩‍💻🔍

Don’t let your resume be the weak link. Discover how to make a strong first impression with our free technical resume review!

Related Articles

ascii value in java

Print ASCII Value in Java

In this article we will into the ASCII table in C, exploring its various character sets—from control characters to printable characters, including letters, digits, and special symbols—and demonstrates how to

data hiding in java

Data Hiding In Java

In this article we will discuss data hiding in Java which is an important concept in object-oriented programming. We will cover So let’s get started. What is Data Hiding in

Why Aren’t You Getting Interview Calls? 📞❌

It might just be your resume. Let us pinpoint the problem for free and supercharge your job search. 

Newsletter

Don’t miss out! Subscribe now

Log In