The final keyword in Java is described in detail

  • 2020-04-01 02:41:08
  • OfStack

The & # 8226; The final variable
If the final keyword is added to a variable, it cannot be changed once the variable is initialized.

If a final variable is a class member variable, it must be initialized and can only be initialized once.

The arguments in the method can also be final variables. This is useful when we need to pass a referential variable, because sometimes we don't want to call a function to change that variable to affect the value of the object in the original function. Therefore, setting the referential variable to final type effectively allows the variable to be modified by the calling parameter. At this point, you can only use this variable in the calling method, but you cannot make any changes to it.


void test(final int a){  
    //can not modify a     

}  

The & # 8226; The final method

If a method ina class is final, subclasses of that class can use the method directly, but cannot override it.


Some compilers, when they call a final method again, simply insert the body of the final method into the call to improve efficiency, rather than saving breakpoints, pushing stacks, and so on.


The & # 8226; Final class

If a class is final, it cannot be inherited. So the final class is a leaf class, it can't be abstract. Methods in final classes are definitely final (but you don't need to explicitly add the final keyword to the method, and of course it doesn't matter), and variables in final classes can be final or non-final.


Related articles: