Table of Contents
ToggleFinal 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 Name | Description |
---|---|
java.lang.String | Represents a sequence of characters, and it’s immutable and widely used for text handling. |
java.lang.Math | Provides mathematical functions and constants as static methods. |
java.lang.System | Offers access to system resources and standard input/output streams. |
java.lang.Integer | Wrapper class for the int primitive data type. |
java.lang.Double | Wrapper class for the double primitive data type. |
java.lang.Boolean | Wrapper class for the boolean primitive data type. |
java.util.Collections | Contains utility methods for working with collections like lists, sets, and maps. |
java.util.Arrays | Provides utility methods for working with arrays. |
java.lang.Enum | Base class for all enumeration types in Java. |
java.time.LocalDate | Represents a date without a time zone. |
java.time.LocalDateTime | Represents a date and time without a time zone. |
java.time.ZonedDateTime | Represents a date and time with a time zone. |
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?
Yes, a final class can be instantiated in Java. You can create objects of a final class, but you cannot extend or subclass it.
What is final object in Java?
There is no such concept as a “final object” in Java. The “final” keyword is used to declare constants, prevent method overriding, and mark classes as non-extendable.
What is the difference between final and static in Java?
“final” is used to make a variable, method, or class unchangeable, while “static” is used to create class-level members (variables and methods) that belong to the class rather than instances.
Is StringBuilder a final class in Java?
No, StringBuilder is not a final class in Java. It can be extended and modified. StringBuilder is used to create mutable strings, allowing you to modify their content.