In Java, the final keyword is used to indicate that a variable, method, or class cannot be modified or extended.
When applied to a variable, the final keyword indicates that the variable’s value cannot be changed once it has been initialized. This makes the variable a constant. Here’s an example:
public class Main {
public static void main(String[] args) {
final int MAX_VALUE = 10;
// MAX_VALUE = 20;
// Compilation error: cannot assign a value to final variable
System.out.println(MAX_VALUE);
}
}
In this example, we declare a constant MAX_VALUE and initialize it with the value 10. Since MAX_VALUE is declared as final, we cannot change its value later in the program. If we try to assign a new value to MAX_VALUE, we get a compilation error.
When applied to a method, the final keyword indicates that the method cannot be overridden by subclasses. Here’s an example:
public class Animal {
public final void makeSound() {
System.out.println("Animal is making a sound");
}
}
public class Dog extends Animal {
// Attempt to override makeSound method
// will result in a compilation error
}
In this example, the makeSound method of the Animal class is declared as final. This means that it cannot be overridden by subclasses such as the Dog class. If we attempt to override the makeSound method in the Dog class, we get a compilation error.
When applied to a class, the final keyword indicates that the class cannot be subclassed. Here’s an example:
public final class MyClass {
// Class definition goes here
}
// Attempt to extend MyClass will result in a compilation error
// public class MySubclass extends MyClass {
// }
In this example, the MyClass class is declared as final, which means that it cannot be subclassed. If we attempt to define a subclass of MyClass called MySubclass, we get a compilation error.
In general, the final keyword is used to indicate that something cannot be modified or extended, which can help prevent bugs and improve code safety. It is commonly used to define constants, prevent method overrides, and prevent class inheritance.