What is the purpose and usage of ‘final’ in Java?
In Java, the keyword ‘final’ is used to modify classes, methods, and variables, indicating that they cannot be changed. Its functionality and usage are as follows:
- Decorating a class: The class decorated with “final” cannot be inherited, meaning that the class is final and cannot have any subclasses. For example: final class MyClass {}
- Method modifiers: final modifier prevents a method from being overridden by subclasses, making the method final. For example:
class Parent {
public final void method() {
// method implementation
}
}
class Child extends Parent {
// 无法重写父类的final方法
}
- Variables modified with ‘final’ keyword represent constants, and can only be assigned a value once, after which they cannot be modified again. For example:
final int num = 10;
num = 20; // 编译错误,无法修改final变量的值
Using the final keyword can enhance the security and readability of code, reduce program complexity, and also aid in performance optimization.