1Z0-819 · Question #146
Given: public class Price { private final double value; public Price(String value) { this(Double.parseDouble(value)); } public Price(double value) { this.value = value; } public Price () { public…
The correct answer is D. 1.99-0.0-2.99. Note: The code as written has a structural defect - the no-arg Price() constructor is never closed, making it malformed. The intended code almost certainly has public Price() {} as an empty constructor body, and value should not be final (a final field not initialized in a…
Question
Options
- AThe compilation fails.
- B1.99-2.99-
- C1.99-2.99-0.0
- D1.99-0.0-2.99
How the community answered
(53 responses)- A9% (5)
- B4% (2)
- C15% (8)
- D72% (38)
Explanation
Note: The code as written has a structural defect - the no-arg Price() constructor is never closed, making it malformed. The intended code almost certainly has public Price() {} as an empty constructor body, and value should not be final (a final field not initialized in a constructor causes a compile error). Assuming those are typos, D is correct because:
p1 = new Price("1.99") chains via this(Double.parseDouble("1.99")) to Price(double), setting value = 1.99. p2 = new Price() uses the empty no-arg constructor, leaving value at Java's default for double: 0.0. p3 = new Price(2.99) directly sets value = 2.99. The println concatenates them in declaration order - p1, p2, p3 - producing 1.99-0.0-2.99.
Why the distractors fail:
- A would be correct as written (due to
final+ uninitialized field), but the question intends a compiling version. - B (
1.99-2.99-) is nonsensical - there's no scenario that produces a trailing dash with a missing third value. - C (
1.99-2.99-0.0) is a trap for students who assume the no-arg constructor somehow callsPrice(2.99), swappingp2andp3's values.
Memory tip: When you see constructor chaining with this(...), trace the delegation chain first - each constructor only assigns value when it reaches the one with this.value = .... Any constructor that doesn't assign value leaves it at its type's default (0.0 for double).
Topics
Community Discussion
No community discussion yet for this question.