Difficulty: Medium
Correct Answer: By using the syntax super.fieldName inside the subclass method to refer to the superclass field.
Explanation:
Introduction / Context:
Field hiding occurs in Java when a subclass declares a field with the same name as a field in its superclass. Interview questions on this topic test understanding of inheritance, access to hidden members, and the use of the super keyword. Knowing how to reach the original superclass field is useful when maintaining legacy code or debugging subtle behavior.
Given Data / Assumptions:
Concept / Approach:
In Java, the super keyword provides a direct way for subclass code to refer to members inherited from the superclass. For methods, super.methodName() invokes the superclass implementation. For fields, super.fieldName accesses the field defined in the superclass, bypassing the field defined in the subclass. This is different from this.fieldName, which always refers to the field as seen in the subclass.
Step-by-Step Solution:
Verification / Alternative check:
Writing a small example with a superclass having an int value field and a subclass having its own int value field, and then printing value, this.value, and super.value from within a subclass method shows the difference. super.value prints the superclass value, confirming that super.fieldName works as intended.
Why Other Options Are Wrong:
Common Pitfalls:
Developers sometimes confuse method overriding with field hiding. Methods are dynamically dispatched, but fields are resolved based on the reference type at compile time. Another pitfall is relying heavily on field hiding, which can make code harder to read; it is usually better to choose different field names or use composition.
Final Answer:
The correct choice is By using the syntax super.fieldName inside the subclass method to refer to the superclass field. because super provides the direct, language supported way to access the hidden superclass field.
Discussion & Comments