In this lesson, you will learn
The keyword final has three uses.
The final use to make variables as constants. This means that once a final variable is initialized, its value cannot be changed.
public class FinalVariableExample {
public static void main(String[] args) {
final int LIMIT = 5;
// LIMIT = 10; // Uncommenting this line
// would cause a compilation error
System.out.println("The limit is: " + LIMIT);
}
}
A final method cannot be overridden by subclasses.
This is useful when you want to lock down the implementation of a method to prevent any subclass from changing its behavior.
public class Animal {
public final void eat() {
System.out.println("This animal eats food.");
}
}
public class Dog extends Animal {
// This method would cause a compilation error if uncommented
//public void eat() {
// System.out.println("This dog eats biscuits.");
//}
}
When a class is declared as final, it cannot be subclassed.
This is particularly useful when creating an immutable class or a class that should not be extended for security reasons.
Example
public final class FinalClass {
// Class body
}
// This would cause a compilation error
//public class AnotherClass extends FinalClass {
// // Attempt to subclass FinalClass
//}
There are no reviews yet. Be the first one to write one.
You must be logged in to submit a review.