nerdexam
Oracle

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

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 Baz extends Bar { public void methodB(String s) { System.out.println("Baz " + s); } } public class Daze extends Baz { private Bar bb = new Bar(); public void methodB(String s) { bb.methodB(s); super.methodB(s); } } public class TestClass { public static void main(String[] args) { Daze d = new Daze(); d.methodB("Hello"); } } What is the result?

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)
  • A
    3% (1)
  • B
    73% (24)
  • C
    9% (3)
  • D
    15% (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:

  1. bb.methodB(s) - bb is declared and instantiated as new Bar(). Both the static and runtime type are Bar, so Java's dynamic dispatch calls Bar.methodB() → prints "Bar Hello"

  2. super.methodB(s) - Inside Daze, super refers directly to Baz. This is a static (non-virtual) super call, so it calls Baz.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)

OptionWhy 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

super skips exactly one level in the inheritance chain, not all the way to the top. And runtime type determines dispatch - new Bar() will always call Bar'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.

Full 1Z0-809 Practice