Middle
Can static methods be overridden in Java?
sobes.tech AI
Answer from AI
In Java, static methods cannot be overridden in the traditional sense because they are associated with the class, not with an instance.
If a static method with the same signature is declared in a subclass, it is called method hiding, not overriding.
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");
}
}
public class Test {
public static void main(String[] args) {
Parent p = new Child();
p.staticMethod(); // Will print "Parent static method"
Child.staticMethod(); // Will print "Child static method"
}
}
Thus, the call to a static method depends on the type of the reference, not the object, and overriding does not occur.