The final keyword can be used to modify classes, variables, and methods.
When final modifies a variable, it means that the variable cannot be changed once the initial value is obtained.
Final member Variable
The final decorated class field, where the instance field can specify the initial value, is as follows:
-> class field: The initial value must be specified in a static initialization block or when the field is declared.
-> instance field: You must specify an initial value in a non-static initialization block, declaring the field, or a constructor.
If you have already specified an initial value for an instance field in a normal initialization block, do not specify an initial value in the constructor for that instance field. Class field in the same vein.
/**
* Final member variable Test
* This program details the final modified member variables in a variety of specific situations * * *
package Chapte5;
public class Finalvariabletest {
//define a member variable to specify a default value, the legal
final int a =;
The following variables are assigned an initial value in the constructor or initialization block, and are legally
final String str;
final int C;
Final static double D;
CH does not specify an initial value when defined, nor does it allocate an initial value in the constructor or initialization block, so that the definition is illegal
//final Char ch;
{
str = "Hello";
}
static{
d=5.6;
}
Public Finalvariabletest () {
c=5;
}
public void Changefinal () {
//cannot specify an initial value or change the initial value//d=1.2 in the normal method for the final variable
;
}
public static void Main (string[] args) {
finalvariabletest ft= new Finalvariabletest ();
System.out.println (FT.D);
System.out.println (FT.A);
}
final local variable
When you use final to modify a local variable, you can specify either a default value or a default value when you define it. If the final-decorated local variable does not specify a default value when it is defined, you can assign the final variable an initial value in the subsequent code fragment, but only once, and cannot repeat the assignment. the difference between the final modifier base type variable and the reference type variable
When you use the final modifier type variable, you cannot assign a value to the base type variable, so the base type variable cannot be changed. For reference to a type variable, it only holds a reference, and final only guarantees that the address referenced by the reference type variable will not change, but that the object can be changed at all. Defining macro Variables
The final variable, if it satisfies three conditions, is no longer a variable, but a direct amount (macro variable):
(1) using final modification;
(2) The initial value is specified when the final variable is defined;
(3) The initial value can be determined at compile time. Final Method
The final modified method cannot be overridden. Final Class
The final decorated class cannot be inherited.