Use of 1.final modifiers:
- Final can modify the variable, and after the final modified variable is assigned the initial value, it cannot be re-assigned.
- Final can modify the method, and the final modified method cannot be overridden.
- Final can modify the class, and the final decorated class cannot be inherited.
The above "grammar formulas" are still not enough to really master the final modifier.
2.final modified variable: The final modified instance variable must display the specified initial value, and the initial value can only be specified in the following three locations:
- Specifies the initial value when defining a final instance variable.
- Specifies 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 construction method.
PackageObjectstudy; Public classFinalinstancevaribaletest {Final intvar1 = 1;//Specifies the initial value when defining a final instance variable. Final intvar2; Final intVar3; //Specifies 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 construction method. Publicfinalinstancevaribaletest () { This. VAR3 = 3; } Public Static voidMain (string[] args) {finalinstancevaribaletest finalinstancevaribaletest=Newfinalinstancevaribaletest (); System.out.println (FINALINSTANCEVARIBALETEST.VAR1); System.out.println (FINALINSTANCEVARIBALETEST.VAR2); System.out.println (FINALINSTANCEVARIBALETEST.VAR3); }}
Use of the final modifier in Java