Junior — Middle
Millistel juhtudel tuleks Java-s kasutada final-muutujat?
sobes.tech AI
Vastus AI-lt
The final modifier in Java is used to restrict changes and enhance code security. It should be applied in the following cases:
- For variables: to make them constants, whose values cannot be changed after initialization.
- For methods: to prevent overriding the method in subclasses, which is important for maintaining logic and preventing errors.
- For classes: to prevent inheritance, which is useful when a class should remain unchanged and protected from extension.
Example:
final class Constants {
public static final double PI = 3.14159;
}
class Base {
public final void show() {
System.out.println("Final method");
}
}
class Derived extends Base {
// Error: cannot override final method show()
}