If a class must not be inherited or its behavior altered, the final keyword can be used to restrict extensibility. Declaring a class as final prevents inheritance, while declaring methods as final prevents method overriding. This helps preserve the original implementation, enforce design constraints, and protect critical business logic from unintended modifications.
The String class in Java is declared as final. This prevents developers from extending it and changing its behavior, helping maintain immutability and security across Java applications.
public final class PaymentProcessor {
public final void processPayment() {
System.out.println(
"Processing Payment");
}
}
class PremiumPaymentProcessor
// extends PaymentProcessor // Compilation Error
{
}A concise interview answer is: To prevent a class from being extended, declare it as final. If only specific behavior must remain unchanged, mark critical methods as final. This ensures the class design remains stable, secure, and protected from unintended modifications.
Last updated: 16 July 2026
Previous question: What is the Java Reflection API, and what is it used for?
Next question: How would you use reflection to implement a simple dependency injection framework?