1Z0-809 · Question #188
public class Foo { public void methodB(String s) { System.out.println("Foo " + s); } } public class Bar extends Foo { public void methodB(String s) { System.out.println("Bar " + s); } } public class…
The correct answer is B. Baz Hello Baz Hello. Before answering, I want to flag that the stated correct answer (B) appears to be wrong based on how Java method dispatch actually works. What Actually Happens When d.methodB("Hello") is called on a Daze instance, Daze.methodB runs two lines: 1. bb.methodB(s) - bb is declared…
Question
Options
- ABaz Hello Foo Hello
- BBaz Hello Baz Hello
- CBaz Hello
- DA compilation error occurs in the Daze class.
How the community answered
(33 responses)- A3% (1)
- B73% (24)
- C9% (3)
- D15% (5)
Explanation
Before answering, I want to flag that the stated correct answer (B) appears to be wrong based on how Java method dispatch actually works.
What Actually Happens
When d.methodB("Hello") is called on a Daze instance, Daze.methodB runs two lines:
-
bb.methodB(s)-bbis declared and instantiated asnew Bar(). Both the static and runtime type areBar, so Java's dynamic dispatch callsBar.methodB()→ prints "Bar Hello" -
super.methodB(s)- InsideDaze,superrefers directly toBaz. This is a static (non-virtual) super call, so it callsBaz.methodB()→ prints "Baz Hello"
Actual output:
Bar Hello
Baz Hello
This matches none of the four options, which suggests there is likely a typo in the original question - bb was probably intended to be new Baz() rather than new Bar(). If bb = new Baz(), both calls would print "Baz Hello" and B would be correct.
Why Each Option Fails (as written)
| Option | Why wrong |
|---|---|
| A (Baz/Foo) | super.methodB in Daze goes to Baz, not Foo |
| B (Baz/Baz) | bb = new Bar() dispatches to Bar.methodB, not Baz.methodB |
| C (Baz only) | Two method calls produce two lines of output |
| D (compile error) | The code compiles fine |
Memory Tip
superskips exactly one level in the inheritance chain, not all the way to the top. And runtime type determines dispatch -new Bar()will always callBar's method regardless of what type the variable is declared as.
I'd recommend double-checking the source of this question, as there may be a typo in the Daze class.
Community Discussion
No community discussion yet for this question.