[Java] finishing the use of final keywords

The role of final

  • In the early use of final, the final method will be converted to inline calls,
    • Inline call: Use one method to call another method. When the compiler finds that the method is final, it will move all the content of the other method, which is equivalent to executing in the same method without calling the method.
    • Because the direct call of the method will have a certain performance loss, it can improve the efficiency of program operation
  • right now:
    • Prevent classes from being inherited, methods from being rewritten, and variables from being modified
    • It is inherently thread-safe without the need for additional synchronization overhead
    • The current JVM will try to optimize the compilation of the code, so the performance improvement brought by the early stage is now negligible

final modified variable

After the attribute is declared as final, the variable can only be assigned once. And once it is assigned, the final variable value cannot be changed.

The timing of assignment is different:
  • Final attributes in the class
    • The first is to directly assign a value to the right of the equal sign of the declared variable
    • The second is to assign values ​​in the constructor
    • The third is to assign values ​​in the initialization code block of the class
    • The timing of the assignment must be selected, and the assignment cannot be omitted, which is stipulated by the final grammar
  • Static final attribute in the class
    • You can assign directly to the right of the equal sign of the declared variable
    • Assign values ​​in static initialization code blocks, not in ordinary initial code blocks
    • Must be assigned
  • Final variables in methods
    • The timing of assignment is not specified, but it must be assigned before use
    • If it is not used, it can not be assigned

final modification method

  • The construction method does not allow final modification
  • Cannot be rewritten

final modified class

  • Cannot be inherited
  • For example String class

Guess you like

Origin blog.csdn.net/weixin_42020386/article/details/107948672