Document directory
- Final data
- Final arguments
- Final Methods
- Final classes
In the sense of final keywords, they cannot be changed. There are two reasons for creating final keywords: 1. design 2. for efficiency (this part is rarely mentioned in the book, and the compiler has greatly improved the efficiency without final after JRE 5 ). The final keyword can be added before data, arguments, method, and Class. The following describes each case.
Final datafinal data means constant. This constant has three types of creation and assignment situations. 1. It can be a compilation constant, and it is directly assigned a fixed value during declaration. For example
private final int valueOne = 1;private static final int VALUE_TWO = 2;
2. However, a runtime constant is assigned an uncertain value during Declaration, for example
private final int valueThree = random.nextInt(10);private static final Value VALUE_FOUR = new Value(7);
3. the blank finals variable can be declared as final, and initialization assignment is not performed during the declaration, but the compiler ensures that all blank final must be initialized before use, for example
public class BlankFinal { private final int valueFive; //black final public BlankFinal() { valueFive = 5; //initialized }}Final arguments can be divided into two situations: 1. if the parameter is primitive type, this parameter cannot be changed within the function. if a parameter is a reference to an object, the referenced object cannot be changed within the function, however, final methods can change the content of the object. Its function is to add a lock to the method so that it cannot be modified when it is inherited. In the past, the final keyword method was used to optimize the efficiency. However, after JRE 5/6, you should discard all the optimization work to the compiler, we encourage you to write final method only because the final classes keyword is added before the class declaration when the method is to be inherited by the Organization, which means you do not want this class to be inherited by anyone. That is to say, this class may not need to be inherited because it does not require more modifications or is in security reasons. Note that all methods in final class are final, although not explicitly indicated.