What is final keyword?
The final keyword in Java is used to define constants, prevent method overriding, and prevent inheritance of classes. It can be applied to variables, methods, and classes, and its behavior varies depending on where it is used.
Uses of final Keyword #
- Final Variables
- Final Methods
- Final Classes
1. Final Variables #
Definition: When a variable is declared as final, its value cannot be changed once it has been initialized. This makes the variable a constant.
Example:
class Constants {
// Final variable
final int MAX_VALUE = 100;
void display() {
System.out.println("Maximum Value: " + MAX_VALUE);
}
}
public class Main {
public static void main(String[] args) {
Constants c = new Constants();
c.display();
// Trying to change the value will cause a compile-time error
// c.MAX_VALUE = 200; // Uncommenting this line will cause a compilation error
}
}
In this example, MAX_VALUE is a final variable, meaning its value cannot be modified after it is initialized.
2. Final Methods #
Definition: A final method cannot be overridden by subclasses. This ensures that the method’s implementation remains unchanged.
Example:
class Animal {
// Final method
final void eat() {
System.out.println("Animal eats food.");
}
}
class Dog extends Animal {
// Trying to override this method will cause a compile-time error
// void eat() { ... } // Uncommenting this line will cause a compilation error
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.eat(); // Outputs: Animal eats food.
}
}
In this example, the eat method in Animal is final, so it cannot be overridden by the Dog class.
3. Final Classes #
Definition: A final class cannot be subclassed. This means no other class can extend a final class.
Example:
// Final class
final class FinalClass {
void display() {
System.out.println("This is a final class.");
}
}
// Trying to extend a final class will cause a compile-time error
// class SubClass extends FinalClass { ... } // Uncommenting this line will cause a compilation error
public class Main {
public static void main(String[] args) {
FinalClass fc = new FinalClass();
fc.display(); // Outputs: This is a final class.
}
}
In this example, FinalClass is a final class, so it cannot be extended by any other class.
Summary #
- Final Variables: Once initialized, their value cannot be changed.
- Final Methods: Cannot be overridden by subclasses.
- Final Classes: Cannot be subclassed.
The final keyword helps enforce immutability, ensure consistent behavior, and prevent unintended modifications or extensions in your Java programs.