•final variables
If you add the final keyword before a variable, once the variable is initialized, it cannot be changed.
If a final variable is a class member variable, it must be initialized and can only be initialized once.
Parameters in methods can also be final variables. This is very useful when we need to pass a reference variable, because sometimes we don't want to call a function to modify the variable and affect the value of the object in the original function. Therefore, setting the reference variable to final type can effectively prevent the variable from being modified by the calling parameters. At this time, the variable can only be used in the calling method, but no modifications can be made to it.
Copy the code code as follows:
void test(final int a){
//can not modify a
}
•final method
If a method in a class is final, subclasses of the class can use this method directly, but cannot override this method.
Some compilers will directly insert the body of the final method into the calling point when calling the final method to improve efficiency, instead of using conventional methods such as saving breakpoints and pushing on the stack.
•final class
If a class is final, it cannot be inherited. Therefore the final class is a leaf class and it cannot be abstract. The methods in the final class must be final (but there is no need to explicitly add the final keyword to the method, of course it doesn't matter if you add it). The variables in the final class can be final or non-final.