The final keyword can be used to enforce strict control over a class design by preventing inheritance and restricting method modification. When a class is declared as final, no other class can extend it. Similarly, when a method is declared as final, subclasses cannot override its implementation. This helps preserve critical business logic and ensures consistent behavior throughout the application.
Key Points: • A final class cannot be inherited, preventing any subclass from modifying its behavior. • A final method can be inherited but cannot be overridden by child classes. • Using final is a common practice in security-sensitive, utility, and immutable classes where behavior must remain unchanged.
Example: The String class in Java is declared as final. This prevents developers from extending it and altering its behavior, which helps maintain security, immutability, and predictable functionality across all Java applications.
Code Example:
final class PaymentProcessor {
public final void processPayment() {
System.out.println("Processing payment...");
}
}
public class Main {
public static void main(String[] args) {
PaymentProcessor processor =
new PaymentProcessor();
processor.processPayment();
}
}Interview Tip: A concise interview answer is: To prevent a class from being extended, declare it as final. To prevent critical methods from being overridden, declare those methods as final. This ensures the class behavior remains fixed, secure, and consistent throughout the application.