Context
In Java, static methods can't be overridden. But in a child class, we can still have the same static method as in the parent class, and the compiler doesn't throw any error about that. In this case, it's not called method overriding; it's called method hiding.
public class Parent {
public static void staticMethod() {
System.out.println("Static method of parent class");
}
public void instanceMethod() {
System.out.println("Instance method of parent class");
}
}
public class Child extends Parent {
public static void staticMethod() {
System.out.println("Static method of child class");
}
@Override
public void instanceMethod() {
System.out.println("Instance method of child class");
}
}
public class App {
public static void main(String[] args) {
Parent p = new Child();
//it invokes an instance method of the child class
p.instanceMethod();
//it invokes a static method of the parent class
p.staticMethod();
}
}
What is the difference?
1.Overriding
Let's take a look at the above example. We can see that the Child class has overridden the 'instanceMethod' in the Parent class. So when we invoke 'p.instanceMethod()', it invokes the method in the Child class instead of the method in the Parent class. This is called polymorphism. Although we declare the variable 'p' with the declared type Parent, we create it as a Child. So, at runtime, the JVM (Java Virtual Machine) finds that 'p' is a Child instance, and it will invoke the method in Child.
2.Hiding
Unlike with overriding, when we invoke 'p.staticMethod()', it invokes the method in the Parent class instead of the Child class. So, what happens here? The static method is resolved at compile time, not at runtime, so it can't exhibit polymorphism. At compile time, 'p' is seen as a Parent instance, while 'p' is only seen as a Child instance at runtime.
Conclusion
We can't override a static method, so when invoking a static method, instead of using 'p.staticMethod()', which can lead to confusion, we should use 'Parent.staticMethod()' or 'Child.staticMethod()' to provide clearer clarification.
Top comments (0)