final
is a keyword in Java, which can be used for variables, methods and classes, and has different meanings:
-
final variables :
- When a variable is declared as
final
, its value cannot be modified, i.e. it is a constant.
final int MAX_VALUE = 100;
final
Once a variable is initialized, it cannot be assigned a value.
- When a variable is declared as
-
final method :
- When a method is declared as
final
, it cannot be overridden (overridden) by subclasses.
class Parent { final void display() { System.out.println("This is a final method."); } } class Child extends Parent { // 以下行会导致编译错误,因为 final 方法不能被重写 void display() { System.out.println("Trying to override final method."); } }
- When a method is declared as
-
final class :
- When a class is declared as
final
, it cannot be inherited.
final class FinalClass { // ... } // 以下行会导致编译错误,因为 final 类不能被继承 class SubClass extends FinalClass { // ... }
- When a class is declared as
-
final parameters :
- In the parameter list of a method,
final
a parameter modified with means that the parameter is read-only, that is, it cannot be reassigned in the method.
void printValue(final int value) { // 以下行会导致编译错误,因为 value 是 final 参数 value = 10; }
- In the parameter list of a method,
final
The main function of keywords is to ensure the immutability of variables, methods or classes, thereby improving the security and reliability of the code. During the development process, reasonable use final
can avoid some unexpected modifications and make the code more robust.