The use of the final modifier in java

  • 2020-08-22 22:05:20
  • OfStack

This article shares the use of final modifiers in java for your reference. The details are as follows

1. Use of final modifier:

final can modify a variable. A variable modified by final cannot be re-assigned after it has been initialized.
final can modify methods, and methods modified by final cannot be overridden.
final can decorate classes, and classes decorated by final cannot be inherited.

The above "grammar tips" are still not enough to really grasp the use of the final modifier.

2.final modified variables: Instance variables modified by final must display the specified initial value and can only be specified in the following three locations:

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


package objectStudy;

public class FinalInstanceVaribaleTest {
 final int var1 = 1;// define final Specifies the initial value of the instance variable. 
 final int var2;
 final int var3;
 
 // Is in a non-static initialization block final An instance variable specifies an initial value. 
 {
 var2 = 2;
 }
 
 //  Is in the constructor final An instance variable specifies an initial value. 
 public FinalInstanceVaribaleTest() {
 this.var3 = 3;
 }
 
 public static void main(String[] args) {
 FinalInstanceVaribaleTest finalInstanceVaribaleTest = new FinalInstanceVaribaleTest();
 System.out.println(finalInstanceVaribaleTest.var1);
 System.out.println(finalInstanceVaribaleTest.var2);
 System.out.println(finalInstanceVaribaleTest.var3);
 }

}

After the compiler processing, the above three methods are extracted into the constructor to assign initial values.

An final class variable can only specify an initial value in two places:

Specify an initial value when defining a variable of the final class.
-- Specifies an initial value for the final class variable in the static initialization block.


Related articles: