In Java, the final keyword is used to indicate that a variable, method, or class cannot be changed or overridden. Once a variable or reference is marked as final, its value cannot be modified. Similarly, once a method or class is marked as final, it cannot be overridden by any subclasses.
Here are some examples of how the final keyword can be used:
public class MyClass {
public static final int MAX\_VALUE = 100;
public void doSomething(final int x) {
final int y = 10;
// MAX\_VALUE = 200; // error: cannot modify final variable
// x = 20; // error: cannot modify final parameter
// y = 30; // error: cannot modify final local variable
}
}
In this example, we declare a final variable MAX_VALUE that cannot be modified. We also declare a final parameter x and a final local variable y, both of which cannot be modified within the method.
public class MyClass {
public final void doSomething() {
// method implementation
}
}
public class MySubclass extends MyClass {
// error: cannot override final method
// public void doSomething() {
// // method implementation
// }
}
In this example, we declare a final method doSomething() in the MyClass class. This method cannot be overridden by any subclasses, as attempting to do so will result in a compilation error.
public final class MyClass {
// class implementation
}
public class MySubclass extends MyClass {
// error: cannot inherit from final class
}
In this example, we declare a final class MyClass that cannot be subclassed. Any attempt to subclass MyClass will result in a compilation error.
In summary, the final keyword is used to indicate that a variable, method, or class cannot be changed or overridden. It is commonly used for constants, immutable objects, and to prevent unintended changes to method or class behavior.