1. Can a static method be overridden?
No, static methods cannot be overridden in Java. This is because method overriding is based on dynamic (runtime) polymorphism, while static methods belong to the class itself, not an instance. Since static methods are resolved at compile time using static binding, overriding them is not possible.
However, you can declare a static method with the same name in a subclass, but this is called method hiding, not overriding.
Example of Method Hiding
class Parent {
static void show() {
System.out.println("Static method in Parent");
}
}
class Child extends Parent {
static void show() { // This hides the Parent's method, not overrides it
System.out.println("Static method in Child");
}
}
public class MethodHidingExample {
public static void main(String[] args) {
Parent p = new Child();
p.show(); // Calls Parent's static method, not Child's
Child c = new Child();
c.show(); // Calls Child's static method
}
}
Output:
Static method in Parent
Static method in Child
Here:
- No overriding occurs, because static methods are resolved at compile time.
p.show()
callsParent
‘s method, even thoughp
is assigned aChild
instance.- This proves that static methods don’t follow runtime polymorphism.
2. Can a static method be overloaded?
Yes, static methods can be overloaded in Java. Method overloading occurs when multiple methods in the same class (or subclass) have the same name but different parameter lists. Since overloading is resolved at compile time, it works with static methods.
Example of Static Method Overloading
class StaticOverloadingExample {
static void print() {
System.out.println("No arguments");
}
static void print(int a) {
System.out.println("Integer argument: " + a);
}
static void print(String s) {
System.out.println("String argument: " + s);
}
public static void main(String[] args) {
print();
print(10);
print("Hello");
}
}
Output:
No arguments
Integer argument: 10
String argument: Hello
Here, three print()
methods exist with different parameters, demonstrating static method overloading.
Key Differences Between Overriding and Overloading of Static Methods
Feature | Static Method Overriding | Static Method Overloading |
---|---|---|
Possible? | ❌ Not possible (only method hiding occurs) | ✅ Possible |
Binding Type | Static binding (compile-time) | Static binding (compile-time) |
Polymorphism Type | No runtime polymorphism | Yes, compile-time polymorphism |
Definition Rule | Same method signature in child class | Same method name, different parameters |
Final Answer
- Overriding static methods? ❌ No, only method hiding happens.
- Overloading static methods? ✅ Yes, it works just like normal method overloading.