1.static Final (constant)
There are two ways to initialize:
(1) Initialize at the time of declaration
Static final i = 1;
You can also set the return value of a static method to it
Static Final int i = f (); Static Public int f () { return 1;}
(2) initialization in the static Code fast (in general, if some code must be executed when the project is started, it is necessary to use static code blocks, this code is actively executed; A class can use a static block of code that is not contained in any method body, and when the class is loaded, a static block of code is executed and executed only once , static blocks are often used to perform initialization of class properties)
Static { = 1; }
2. Final
The final modified variable indicates that the value of the variable cannot be changed; When the method is decorated, it means that the method cannot be overridden by a class override (but can be overloaded in the same class), and when the class is decorated, it means that the class cannot be overloaded
There are three ways to initialize the final, with the first two being the same as the static final, except that the second code quickly removes the static and simply writes {}
There is one more way to do final initialization in a constructor, such as:
Private Final int T; Public Test () { // Suppose the code is in the test class t = 2;} public test (int i) { = i}
When modifying a variable, the difference between final and static final is that final belongs to only that class-specific object, while static final belongs to the class, independent of the specific object.
It is noted that if there are multiple constructors, each of them will be initialized with the final variable, otherwise it will fail.
Here's why you can do that? Because final is not a static variable, but an immutable variable that belongs to a particular class, the creation of the object must pass the constructor, so as long as we initialize the final variable in each constructor, we can ensure that the final variable is initialized successfully and will not be initialized multiple times.
Stactic initialization of final and final variables (in Java)