Junior — Middle
Is it possible to declare methods as final, and in what cases does it make sense?
sobes.tech AI
Answer from AI
In Java and Kotlin (commonly used in Android development), a method can be declared as final to prevent it from being overridden in subclasses. This is useful when you need to guarantee that the behavior of the method remains unchanged, for example, to ensure security, prevent errors, or optimize.
Example:
public class Base {
public final void doSomething() {
// important logic that cannot be changed
}
}
public class Derived extends Base {
// attempting to override doSomething() will cause a compile-time error
}
Purpose of using final:
- Protect critical methods from modification.
- Improve performance (JVM can optimize calls to final methods).
- Simplify code understanding, as the method's behavior is fixed.