Understanding the `final` Keyword in Java

使用して回答:GPT-4o-mini によってJava Q&A Hub

質問:

What is the final variable in Java?

回答:

In Java, the final keyword is used to declare constants or to restrict the modification of variables, methods, and classes. When a variable is declared as final, it means that once it has been assigned a value, it cannot be changed (i.e., it becomes a constant). Here are the different contexts in which final can be used:

  1. Final Variables: When a variable is declared as final, it can only be assigned once. After that, any attempt to change its value will result in a compilation error.

    final int x = 10;
    // x = 20; // This will cause a compilation error
    
  2. Final Methods: A method declared as final cannot be overridden by subclasses. This is useful when you want to prevent modification of a method's behavior in derived classes.

    class Base {
        final void display() {
            System.out.println("This is a final method.");
        }
    }
    
    class Derived extends Base {
        // void display() { // This will cause a compilation error
        //     System.out.println("Trying to override.");
        // }
    }
    
  3. Final Classes: A class declared as final cannot be subclassed. This is useful for creating immutable classes or to prevent inheritance.

    final class FinalClass {
        // Class implementation
    }
    
    // class SubClass extends FinalClass { // This will cause a compilation error
    // }
    
  4. Final Parameters: You can also declare method parameters as final, which means that the parameter cannot be reassigned within the method.

    void myMethod(final int param) {
        // param = 5; // This will cause a compilation error
    }
    

In summary, the final keyword in Java is a way to enforce immutability and prevent changes to variables, methods, and classes, providing a level of safety and predictability in your code.