Junior — Middle
In what cases and how can the keyword final be used in Java?
sobes.tech AI
Answer from AI
The final keyword in Java is used to restrict modifications and enhance code safety. It can be applied to variables, methods, and classes:
-
Variables: declared as
finalcannot be changed after initialization. This is useful for creating constants or protecting against accidental value changes.final int MAX_COUNT = 10; // MAX_COUNT = 20; // Compilation error -
Methods: if a method is declared as
final, it cannot be overridden in subclasses. This ensures the method's behavior remains unchanged.class Parent { public final void show() { System.out.println("Final method"); } } class Child extends Parent { // public void show() {} // Error: cannot override final method } -
Classes: a class declared as
finalcannot be inherited. This is used to prevent class extension.public final class Utility { // code } // class ExtendedUtility extends Utility {} // Compilation error
Using final helps make the code more predictable and protected from unwanted changes.