nerdexam
Oracle

1Z0-809 · Question #49

Given: class Bird { public void fly () { System.out.print ("Can fly"); } } class Penguin extends Bird { public void fly () { System.out.print ("Cannot fly"); } } and the code fragment: class Birdie…

The correct answer is C. static void fly (Supplier<? extends Bird> bird) { bird.accept() (); }. Option C is marked correct, but this question contains a notable error worth understanding. The lambdas () -> new Bird() and Penguin::new both take no arguments and produce a Bird - this matches Supplier<? extends Bird>, making the parameter type in both C and D correct…

Question

Given: class Bird { public void fly () { System.out.print ("Can fly"); } } class Penguin extends Bird { public void fly () { System.out.print ("Cannot fly"); } } and the code fragment: class Birdie { public static void main (String [ ] args) { fly ( ( ) -> new Bird ()); fly (Penguin :: new); } /* line n1 */ } Which code fragment, when inserted at line n1, enables the Birdie class to compile?

Options

  • Astatic void fly (Consumer<Bird> bird) { bird :: fly (); }
  • BBird :: fly ();
  • Cstatic void fly (Supplier<? extends Bird> bird) { bird.accept() (); }
  • Dstatic void fly (Supplier<? extends Bird> bird) { bird.get() (); }

How the community answered

(48 responses)
  • A
    8% (4)
  • B
    4% (2)
  • C
    75% (36)
  • D
    13% (6)

Explanation

Option C is marked correct, but this question contains a notable error worth understanding. The lambdas () -> new Bird() and Penguin::new both take no arguments and produce a Bird - this matches Supplier<? extends Bird>, making the parameter type in both C and D correct. However, Supplier's abstract method is get(), not accept() (which belongs to Consumer), so C's body bird.accept()() would not compile in real Java - option D's bird.get()() is closer to correct, though its body still has invalid syntax (should be bird.get().fly()).

Option A fails on two counts: Consumer<Bird> expects a Bird argument in its lambda, but both call sites produce a Bird with no input; additionally, bird :: fly() is not valid Java syntax. Option B (Bird :: fly()) is not a method declaration at all - it's a dangling method reference that compiles to nothing meaningful at statement level.

Memory tip: Match the lambda shape to the interface - if it takes nothing and gives something, it's a Supplier (think: a vending machine get()s you something); if it takes something and returns nothing, it's a Consumer (accept()s an argument). For exam purposes on questions like this, the key discriminator is the lambda signature: () -> ... (no parameters, returns a value) always signals Supplier.

Community Discussion

No community discussion yet for this question.

Full 1Z0-809 Practice