Sobes.tech
Junior

What does the keyword 'final' mean in the Java programming language?

sobes.tech AI

Answer from AI

The final keyword in Java is used to indicate that a variable, method, or class cannot be modified.

  1. final variable:

    • A variable declared as final can only be assigned once. After assignment, it cannot be changed.
    • For primitive data types, the value of a final variable is a constant.
    • For reference types, a final variable means that the reference cannot be changed, but the state of the object it points to can be modified (unless the object's fields are also declared as final).
    final int MAX_VALUE = 100; // final primitive variable
    
    final List<String> names = new ArrayList<>(); // final reference variable
    names.add("Alice"); // OK
    // names = new ArrayList<>(); // Compilation error - cannot reassign the reference
    
  2. final method:

    • A method declared as final cannot be overridden in subclasses.
    • This is used to prevent unwanted changes in behavior within an inheritance hierarchy.
    class Parent {
        final void display() {
            System.out.println("This is a final method.");
        }
    }
    
    class Child extends Parent {
        // @Override void display() { } // Compilation error - cannot override a final method
    }
    
  3. final class:

    • A class declared as final cannot have subclasses (cannot be inherited).
    • This is used to ensure the immutability of the class and prevent extending its functionality.
    final class ImmutableClass {
        private final int value;
    
        public ImmutableClass(int value) {
            this.value = value;
        }
    
        public int getValue() {
            return value;
        }
    }
    
    // class TryingToExtend extends ImmutableClass { } // Compilation error - cannot inherit a final class