Junior — Middle
Explain what the keyword 'final' means in the Java language and in which cases it is used.
sobes.tech AI
Answer from AI
In Java, the keyword final is used to denote immutability or prohibition of overriding in different contexts:
-
For variables: a variable declared as
finalcan only be initialized once. After assignment, the value cannot be changed.final int x = 10; // x = 20; // compilation error -
For methods: a method declared as
finalcannot be overridden in subclasses.class Base { public final void show() { System.out.println("Base show"); } } class Derived extends Base { // public void show() {} // compilation error } -
For classes: a class declared as
finalcannot have subclasses.public final class Utils { // ... } // class MyUtils extends Utils {} // compilation error
final is used to ensure safety, prevent modifications, improve readability, and optimize the compiler.