Introduction to the use of final and finally in Java

  • 2020-04-01 01:50:54
  • OfStack

Final can modify classes, member variables, local variables, and methods.

1. Final modifies member variables

1. Initialization of final member variables

For variables that are final modified, the system does not initialize to 0 by default

Fina variable initialization method:

Initialize at definition time Final variables can be initialized in an initialization block, not ina static initialization block. Static final variables can be initialized ina static initialization block, not in an initialization block. Fina variables can also be initialized in the constructor, but static final variables cannot.

2. Final modification method

When final is used to modify a method, it means that the method cannot be overridden by a subclass.

3. The final class

  Columns that are final are not allowed to be inherited, and the compiler treats all of its methods as if they were final, so final is more efficient than regular classes. An abstract column defined by the keyword abstract contains abstract methods that must be implemented by its subclass overloading, so you cannot modify the same class with final and abstract at the same time. By the same token, final cannot be used to modify an interface. Methods of final classes cannot be overridden. This does not mean that the property values of the final class are immutable. To make the property value of a final class immutable, you must add the final modifier.

The finally statement can only be used ina try/catch statement and comes with a block that indicates that the statement is always executed eventually.


public class Test {
     public static void main(String[] args){
         System.out.println(returnTest());//false
     }
     public static boolean returnTest(){
         try{
             return true;
         }finally{
             return false;
         }
     }
 }

Calculate the value of the expression after return, temporarily store the value, then calculate the value of the expression after return in finally, and then temporarily store it,
At this point, the stored values are overwritten. Finally, go back to the previous return, take out the value from where the variable was temporarily stored, and return. This is the result.


Related articles: