In this article, I will be covering Java’s final keyword. I will be demonstrating the final keyword in Java with an example.
You can use the final keyword with a method or instance field. When you use it with a method, it prevents the method from being overridden. When you use it with a field, it prevents the field from being modified.
public class Base {
public final void show() {
System.out.println("In show”);
}
}
public class Sub extends Base {
// This method causes a compilation error
public void show() {
}
}
}
Declaring a variable as final prevents its contents from being modified. This means that you must initialize a final variable when it is declared.
The following code demonstrates a final field:
public void aMethod() {
final int d = 10;
d = 3; // compilation error
}
So, in this article, we saw why final keyword is used in Java.