In Java, the keyword final can be applied to variables, methods, and classes, with different effects. Below I'll detail what each does and provide relevant code demonstrations.
1. final variable:
· When applied to a variable, the final keyword indicates that the value of the variable cannot be modified, that is, it is a constant. Once a final variable is assigned an initial value, it cannot be changed.
Final variables must be initialized at the time of declaration, and can be assigned directly at the time of declaration or assigned in the constructor.
Final variables are usually named with uppercase letters, and multiple words are separated by underscores.
Sample code:
public class FinalVariableExample {
public static void main(String[] args) {
final int MAX_COUNT = 10;
// MAX_COUNT = 20; // 编译错误,无法修改final变量的值
System.out.println(MAX_COUNT);
}
}
2. final method:
· When applied to a method, the final keyword indicates that the method cannot be overridden by subclasses. That is, subclasses cannot change or extend final methods.
The final method is useful for the stability and security of the class design, preventing subclasses from changing the key logic of the parent class.
Sample code:
public class FinalMethodExample {
public final void printMessage() {
System.out.println("Hello, World!");
}
}
class SubClass extends FinalMethodExample {
// @Override // 编译错误,无法重写final方法
public void printMessage() {
System.out.println("This is a subclass.");
}
}
3. final class:
When applied to a class, the final keyword indicates that the class cannot be inherited, that is, it is the final class and cannot have subclasses.
Final classes are usually used for security or design considerations to prevent other classes from extending or modifying them.
Sample code:
public final class FinalClassExample {
// ...
}
class SubClass extends FinalClassExample {
// 编译错误,无法继承final类
}
These are the main usage and role of final keyword in Java. By using the final keyword, functions such as constants, preventing method rewriting, and class inheritance can be realized, thereby improving the readability, maintainability, and security of the code.