Junior — Middle
Can a static class method be declared as final to prevent it from being overridden?
sobes.tech AI
Answer from AI
In Java, static methods cannot be overridden in subclasses because they belong to the class itself, not to an instance. Therefore, declaring a static method as final does not make sense and is syntactically not allowed.
The keyword final is usually used for instance methods to prevent them from being overridden in subclasses. For static methods, overriding is impossible, but a method with the same name can be hidden in the subclass (this is called method hiding).
Example:
class Parent {
static void staticMethod() {
System.out.println("Parent static method");
}
}
class Child extends Parent {
static void staticMethod() {
System.out.println("Child static method");
}
}
Here, Child hides the Parent method, but this is not overriding. Declaring final for a static method is not allowed.