“This is the first day of my participation in the August More Text Challenge.

Final is a reserved keyword in Java that allows you to declare member variables, methods, classes, and local variables. Once you have made the reference declaration final, you cannot change the reference, the compiler checks the code, and if you try to initialize the variable again, the compiler will report a compilation error.

Basic usage of the final keyword

1. Modify variables

Any member variable or local variable (called local ina method or code block) that is declared final is called final. Final variables are often used with the static keyword as constants.

When final modifies a variable of a basic data type, it must be given an initial value and cannot be changed. When modifying a reference variable, the reference variable cannot point to another object

Such as:

An error is reported when final modifies a primitive datatype variable without assigning an initial value and when the reference variable points to another object

An error is reported when a final modifier base datatype variable is changed

2

Final can also declare methods. Methods preceded by the final keyword cannot be overridden by subclass methods. You can declare a method final if you think its functionality is complete enough that it doesn’t need to be changed in subclasses. Final methods are faster than non-final methods because they are already statically bound at compile time and do not need to be dynamically bound at run time.

3. The modified classes

Classes decorated with final are called final classes. Final classes are usually fully functional; they cannot be inherited. There are many classes in Java that are final, such as String, Interger, and other wrapper classes.

Two. In-depth analysis of the final keyword

1. The content of an object modified by final is mutable

Even though an object is final an object cannot be inherited, its contents can still be changed

2. Compare final keyword with static keyword

The static keyword modifies a variable so that it is initialized when the class is loaded and not reloaded when the object is created. It is initialized only once

For example, as shown in the figure, the variable j that is modified static does not change its value even though two objects are created.