In Java, final classes and methods are used to restrict inheritance and prevent modifications in subclasses. This is useful when you want to ensure that class or its behaviour does not change.
Prerequisite:
1. Final Classes
A class declared as final cannot be extended (cannot inherit it). As the name suggests, this is used for final classes (critical or sensitive classes) whose behaviour is final and remains unchanged.
Syntax
final class Parent {
void display() {
System.out.println("This is a final class");
}
}
class Child extends Parent { // Error: Cannot inherit from final 'Parent'
}
Where this needs to be used:
- Security: classes that deals with the sensitive data such as user personal information.
- Immutability: For immutable classes to ensure that no subclass can modify the behaviour (e.g.,
String
class in Java).
2. Final Methods
A final
method cannot be overridden in a subclass. This ensures that a specific implementation of the specific method remains same for all the derived classes. Let’s say you want to declare a method in class so that it can be used in child classes but you don’t want the child classes to alter the method definition.
Syntax
class Parent {
final void display() {
System.out.println("This is a final method");
}
}
class Child extends Parent {
// void display() { // Error: Cannot override final method
// System.out.println("Overriding not allowed");
// }
}
Use Cases
- Preserve Behavior: Prevent subclasses from altering critical logic.
- Enforce Consistency: To make the method work same in all sub classes.
3. Final Variables in Inheritance
Error: This would ensure that the value of final variable remains unchanged in sub classes. A subclass cannot alter the value of the final variable.
class Parent {
final int NUM = 10;
}
class Child extends Parent {
void update() {
// NUM = 20; // Error: Cannot assign a value to final variable 'NUM'
}
}
4. Rules for Final Classes and Methods
- A
final
method can be inherited but not overridden. - If a class is declared as
final
, all its methods are implicitly final. - Constructors cannot be declared as
final
because they are not inherited.
5. Examples of Final Classes in Java
- Built-in Final Classes: Many Java standard library classes are
final
, such as:String
Integer
Double
- These classes are immutable, and their
final
status makes their behaviour consistent among sub classes.
6. Best Practices
- Use
final
classes or methods for immutability and security. - Avoid overusing
final
, as it reduces flexibility in inheritance. - When designing an API, carefully decide which classes and methods should be
final
to balance extensibility and control.
Leave a Reply