1Z0-819 · Question #24
Given: public class Foo { public void foo(Collection arg) { System.out.println("Bonjour le monde!"); } } and public class Bar extends Foo { public void foo(Collection arg) {…
The correct answer is D. b1.foo(c) prints Hello world! H. f2.foo(c) prints Hello world! I. f1.foo(c) prints Bonjour le monde! This question tests two core Java concepts simultaneously: runtime polymorphism (overriding) and compile-time overload resolution (overloading). Why D, H, and I are correct: I (f1.foo(c) → "Bonjour le monde!"): f1 is declared and actually instantiated as Foo, so it calls…
Question
Options
- Ab1.foo(c) prints Bonjour le monde!
- Bf1.foo(c) pr ts Hello world!
- Cf1.foo(c) prints Hola Mundo!
- Db1.foo(c) prints Hello world!
- Eb1.foo(c) prints Hola Mundo!
- Fb1.foo(c) prints Olá Mundo!
- Gf2.foo(c) prints Bonjour le monde!
- Hf2.foo(c) prints Hello world!
- If1.foo(c) prints Bonjour le monde!
How the community answered
(26 responses)- A8% (2)
- C4% (1)
- D73% (19)
- G15% (4)
Explanation
This question tests two core Java concepts simultaneously: runtime polymorphism (overriding) and compile-time overload resolution (overloading).
Why D, H, and I are correct:
- I (
f1.foo(c)→ "Bonjour le monde!"):f1is declared and actually instantiated asFoo, so it callsFoo.foo(Collection)- straightforward. - H (
f2.foo(c)→ "Hello world!"):f2is declared asFoobut instantiated asBar. At compile time, the compiler seesFoo'sfoo(Collection)signature. At runtime, dynamic dispatch kicks in and executesBar's overriding version, printing "Hello world!". - D (
b1.foo(c)→ "Hello world!"):b1isBar, which has bothfoo(Collection)andfoo(List). The argumentcis declared asCollection<String>- its compile-time type isCollection, notList. SinceCollectiondoes not satisfyList, the compiler selectsfoo(Collection), printing "Hello world!".
Why the distractors fail:
- A/G are wrong because
Baroverridesfoo(Collection), so "Bonjour le monde!" never prints for anyBarinstance (orFooreference holding aBar). - B/C are wrong because
f1is genuinely aFooobject with no overriding - it always prints "Bonjour le monde!". - E is the key trap: even though
cis actually anArrayList(which implementsList), overload selection happens at compile time using the declared typeCollection.Foo(List)is never chosen, so "Hola Mundo!" never prints. - F is a distractor - no such method exists anywhere.
Memory tip: Remember "override = runtime, overload = compile time." When you see a method call, ask two questions in order: (1) Which overload does the compiler pick based on the declared argument types? (2) Which override does the JVM execute based on the actual object type?
Topics
Community Discussion
No community discussion yet for this question.