Explain the use of the final keyword in variable, method and class in Java.
In Java, the final
keyword is used to define constants, prevent method overriding, and prevent inheritance. It can be applied to variables, methods, and classes, each serving a different purpose. Here’s a detailed explanation of its use in each context:
When a variable is declared as final
, it means that its value cannot be changed once it has been assigned. This is often used to define constants.
Example:
final int MAX_VALUE = 100;
// MAX_VALUE = 200; // This will cause a compilation error
final
variable must be initialized when it is declared or in the constructor if it is an instance variable.final
variable cannot be modified.A method declared as final
cannot be overridden by subclasses. This is useful when you want to ensure that the behavior of a method remains consistent and cannot be altered.
Example:
class Parent {
final void display() {
System.out.println("This is a final method.");
}
}
class Child extends Parent {
// void display() { // This will cause a compilation error
// System.out.println("Trying to override.");
// }
}
final
method can still be inherited, but it cannot be overridden.A class declared as final
cannot be subclassed. This is useful when you want to prevent inheritance for security reasons or to maintain the integrity of the class.
Example:
final class FinalClass {
// Class implementation
}
// class SubClass extends FinalClass { // This will cause a compilation error
// }
final
class cannot have any subclasses.Using the final
keyword appropriately can help in designing robust and maintainable Java applications by enforcing certain constraints on variables, methods, and classes.