A final class in Java is a class that cannot be subclassed. When a class is declared as final, it is considered “closed” for inheritance, meaning no other class can extend it. This is used to ensure that the class’s functionality cannot be altered by creating derived classes.
Syntax of Final Class
To declare a class as final, use the final keyword before the class keyword:
final class FinalClass {
// Fields, constructors, and methods
void display() {
System.out.println(“This is a final class.”);
}
}
Key Characteristics of Final Class
- Prevents Inheritance: No class can extend a final class.
- Can Be Instantiated: A final class can still have objects created from it.
- Can Have Final Methods: Methods in a final class can also be declared as final to prevent overriding, but it’s unnecessary as no subclass can override them anyway.
- Immutable Classes: Final classes are often used to create immutable classes like String.
Why Use Final Classes?
- Security: Prevents unauthorized extension and modification of sensitive classes.
- Immutability: Useful for creating immutable objects like those in the String or Wrapper classes (Integer, Double, etc.).
- Optimization: Allows the compiler to apply certain optimizations as it knows the class will not be extended.
Examples
Example 1: Declaring a Final Class
final class Vehicle {
void display() {
System.out.println(“This is a final class.”);
}
}
// Attempt to extend a final class
// class Car extends Vehicle { // Error: Cannot inherit from final ‘Vehicle’
// }
public class Main {
public static void main(String[] args) {
Vehicle vehicle = new Vehicle();
vehicle.display(); // Output: This is a final class.
}
}
Example 2: Final Class in Built-in Java Library
Many classes in Java’s standard library are final, such as:
- String
- Integer
- Double
For instance:
public class Main {
public static void main(String[] args) {
String str = “Hello, World!”;
System.out.println(str.toUpperCase()); // Output: HELLO, WORLD!
// class MyString extends String { // Error: Cannot inherit from final ‘String’
// }
}
}
Difference Between Final Class and Final Method
Feature | Final Class | Final Method |
Definition | A class that cannot be subclassed. | A method that cannot be overridden. |
Usage | Used to prevent inheritance. | Used to prevent method overriding. |
Scope of Restriction | Restricts inheritance at the class level. | Restricts inheritance at the method level. |
Disadvantages of Final Classes
- Lack of Extensibility: It limits flexibility as you cannot extend the class for further customization.
- Less Reusability: Code reuse through inheritance is not possible.
When to Use Final Classes
- To define classes that should not be extended (e.g., utility classes like Math or security-sensitive classes).
- To enforce immutability (e.g., String class).
- To ensure the behavior of a class remains unaltered in any context.
By using final classes judiciously, you can make your Java applications more secure and predictable.