SoFunction
Updated on 2025-03-08

How to use final modifier in java

This article shares the use of final modifiers in Java for your reference. The specific content is as follows

Use of modifiers:

Final can modify variables. After the initial value is assigned to the variable modified by final, it cannot be reassigned.
Final can modify the method, and final modified method cannot be rewritten.
Final can modify classes, but classes modified by final cannot be inherited.

The above "grammatical formulas" are still not enough to truly master the usage of final modifiers.

Modified variables:The instance variable modified by final must display the specified initial value, and can only specify the initial value in the following three positions:

Specifies the initial value when defining the final instance variable.
Specify the initial value for the final instance variable in a non-static initialization block.
Specify the initial value for the final instance variable in the constructor.

package objectStudy;

public class FinalInstanceVaribaleTest {
 final int var1 = 1;//Specify the initial value when defining final instance variable. final int var2;
 final int var3;
 
 //Specify the initial value for the final instance variable in a non-static initialization block. {
 var2 = 2;
 }
 
 // Specify the initial value for the final instance variable in the constructor. public FinalInstanceVaribaleTest() {
 this.var3 = 3;
 }
 
 public static void main(String[] args) {
 FinalInstanceVaribaleTest finalInstanceVaribaleTest = new FinalInstanceVaribaleTest();
 (finalInstanceVaribaleTest.var1);
 (finalInstanceVaribaleTest.var2);
 (finalInstanceVaribaleTest.var3);
 }

}

After the compiler's processing, the above three methods will be extracted into the constructor to assign initial values.

The final class variable can only specify initial values ​​in two places:

--Specify the initial value when defining final class variables.
--Specify the initial value for the final class variable in the static initialization block.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.