1Z0-808 · Question #12
Given: class Vehicle { int x; Vehicle() { this(10); // line n1 } Vehicle(int x) { this.x = x; } } class Car extends Vehicle { int y; Car() { super(); this(20); // line n2 } Car(int y) { this.y = y…
The correct answer is D. Compilation fails at line n2. Option D is correct because this(20) at line n2 violates the Java rule that a constructor invocation (this() or super()) must be the first statement in a constructor - having super() already occupy that position makes this(20) illegal, causing a compilation error. Options A and…
Question
Options
- A10:20
- B0:20
- CCompilation fails at line n1
- DCompilation fails at line n2
How the community answered
(27 responses)- A15% (4)
- B4% (1)
- C4% (1)
- D78% (21)
Explanation
Option D is correct because this(20) at line n2 violates the Java rule that a constructor invocation (this() or super()) must be the first statement in a constructor - having super() already occupy that position makes this(20) illegal, causing a compilation error.
Options A and B are wrong because the code never compiles, so no output is ever produced. Option C is wrong because line n1 is perfectly valid: this(10) is the first statement in Vehicle(), which is exactly where a delegating constructor call must appear.
Memory tip: Think of it as "one door in" - a Java constructor gets exactly one entry point, so you can call super() or this(), never both. If you see two constructor calls in the same constructor body, the second one is always the culprit.
Topics
Community Discussion
No community discussion yet for this question.