nerdexam
Oracle

1Z0-829 · Question #22

Given: public class Test { static interface Animal { } static class Dog implements Animal { } private static void play(Animal a) { System.out.print("flips"); } private static void play(Dog d) {…

The correct answer is B. Compilation fails. Option B is correct because a2 is never declared in the code - main references play(a2) but only a1 is defined, causing a "cannot find symbol" compile-time error before any method dispatch logic even runs. Options A, C, D, and E all assume the program compiles and executes…

Java Object-Oriented Approach

Question

Given: public class Test { static interface Animal { } static class Dog implements Animal { } private static void play(Animal a) { System.out.print("flips"); } private static void play(Dog d) { System.out.print("runs"); } public static void main(String[] args) { Animal a1 = new Dog(); play(a1); play(a2); } } What is the result?

Options

  • Aflipsflips
  • BCompilation fails
  • Cflipsruns
  • Drunsflips
  • Erunsruns

How the community answered

(40 responses)
  • B
    90% (36)
  • C
    3% (1)
  • D
    5% (2)
  • E
    3% (1)

Explanation

Option B is correct because a2 is never declared in the code - main references play(a2) but only a1 is defined, causing a "cannot find symbol" compile-time error before any method dispatch logic even runs.

Options A, C, D, and E all assume the program compiles and executes, which it cannot. If you mentally "fix" the code by replacing a2 with a1, the interesting method overloading question would apply: since a1 is declared as type Animal (not Dog), the compiler resolves overloads at compile time based on the declared type, so both calls would dispatch to play(Animal) and print "flipsflips" - making A the answer to that hypothetical, and ruling out C, D, and E.

Memory tip: In Java, overload resolution uses the declared (static) type, not the runtime type - that's polymorphism vs. overloading. But before any of that matters, always check: does every variable exist? A missing declaration kills compilation instantly.

Topics

#method overloading#variable declaration#compile-time type resolution#undefined variable

Community Discussion

No community discussion yet for this question.

Full 1Z0-829 Practice