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
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.
Respecting Choices Embracing the Decisions We Make In life, we often encounter moments where we…
In a world where heroes are celebrated, sometimes the true heroines go unnoticed. Every girl…
In the grand symphony of existence, where life intertwines with love in a dance of…
Introduction Embarking on a journey into the world of programming can be both exciting and…
Exploring the Output of a Python Code Snippet What will be the output of the…
Exploring the code snippet and its functionality In Java, determining the length of a string…