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.
-
finalvariable:- A variable declared as
finalcan only be assigned once. After assignment, it cannot be changed. - For primitive data types, the value of a
finalvariable is a constant. - For reference types, a
finalvariable 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 asfinal).
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 - A variable declared as
-
finalmethod:- A method declared as
finalcannot 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 } - A method declared as
-
finalclass:- A class declared as
finalcannot 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 - A class declared as