The final keyword in Java makes variables, methods and classes unchangeable. Variables cannot be reassigned, methods cannot be overridden, and classes cannot be inherited.
The role of final in Java
In Java, the final keyword is an access modifier, used Used to mark variables, methods, and classes to make them immutable.
Variables
When declaring a final variable, it must be initialized at the time of declaration, and the variable cannot be reassigned later. This ensures that the value of the variable remains unchanged throughout the execution of the program.
For example:
<code class="java">final int MY_CONSTANT = 10; MY_CONSTANT++; // 编译错误:不能重新赋值 final 变量</code>
Method
When final is applied to a method, it means that the method cannot be overridden by subclasses. This is useful to prevent subclasses from modifying key methods in the parent class.
For example:
<code class="java">class Parent { final void printMessage() { System.out.println("Parent message"); } } class Child extends Parent { // 编译错误:无法覆盖 final 方法 void printMessage() { System.out.println("Child message"); } }</code>
Class
If final is applied to a class, it means that the class cannot be inherited. This prevents other classes from subclassing this class.
<code class="java">final class FinalClass { // ... } // 编译错误:无法继承 final 类 class Child extends FinalClass { // ... }</code>
The above is the detailed content of What is the use of final in java. For more information, please follow other related articles on the PHP Chinese website!