Understanding Static Method Binding in Java
Analyzing the Output of a Java Code Snippet
What will be the output of the following Java code?
class Base {
public static void show() {
System.out.println("Base::show() called");
}
}
class Derived extends Base {
public static void show() {
System.out.println("Derived::show() called");
}
}
public class Main {
public static void main(String[] args) {
Base b = new Derived();
b.show();
}
}
JavaOptions:
A. Base::show() called
B. Derived::show() called
C. Compilation Error
D. Runtime Error
Correct Answer: A. Base::show() called
Explanation:
The correct answer is option A. Base::show() called. This outcome can be explained by the concept of static method binding in Java.
In Java, static methods are bound at compile time based on the static type of the reference variable, rather than the runtime type of the object. In the given code, the variable b
is of type Base
but references an object of type Derived
. Despite the dynamic binding nature of instance methods, static methods are not overridden but hidden.
Therefore, when b.show()
is called, the static method show()
of the Base
class is invoked, not the one in the Derived
class.
Understanding the behavior of static method binding is crucial in Java to ensure correct method invocations and proper class hierarchy handling.