final keyword in Java (just read this article)

finalis a keyword in Java, which can be used for variables, methods and classes, and has different meanings:

  1. final variables :

    • When a variable is declared as final, its value cannot be modified, i.e. it is a constant.
    final int MAX_VALUE = 100;
    
    • finalOnce a variable is initialized, it cannot be assigned a value.
  2. final method :

    • When a method is declared as final, it cannot be overridden (overridden) by subclasses.
    class Parent {
          
          
        final void display() {
          
          
            System.out.println("This is a final method.");
        }
    }
    
    class Child extends Parent {
          
          
        // 以下行会导致编译错误,因为 final 方法不能被重写
        void display() {
          
          
            System.out.println("Trying to override final method.");
        }
    }
    
  3. final class :

    • When a class is declared as final, it cannot be inherited.
    final class FinalClass {
          
          
        // ...
    }
    
    // 以下行会导致编译错误,因为 final 类不能被继承
    class SubClass extends FinalClass {
          
          
        // ...
    }
    
  4. final parameters :

    • In the parameter list of a method, finala parameter modified with means that the parameter is read-only, that is, it cannot be reassigned in the method.
    void printValue(final int value) {
          
          
        // 以下行会导致编译错误,因为 value 是 final 参数
        value = 10;
    }
    

finalThe main function of keywords is to ensure the immutability of variables, methods or classes, thereby improving the security and reliability of the code. During the development process, reasonable use finalcan avoid some unexpected modifications and make the code more robust.

Guess you like

Origin blog.csdn.net/yang_guang3/article/details/133295940