1Z0-808 · Question #17
Given the code fragment: public class Person { String name; int age = 25; public Person(String name) { //line n1 this(); setName(name); } public Person(String name, int age) { //line n2…
The correct answer is D. Compilation fails at both line n1 and line n2. Option D is correct because both constructors contain invalid constructor chaining calls. At line n1, this() attempts to invoke a no-argument constructor, but none is defined in the class - the compiler has no Person() to delegate to. At line n2, Person(name) is simply not…
Question
Options
- AJesse 25 Walter 52
- BCompilation fails only at line n1
- CCompilation fails only at line n2
- DCompilation fails at both line n1 and line n2
How the community answered
(37 responses)- A5% (2)
- B16% (6)
- C8% (3)
- D70% (26)
Explanation
Option D is correct because both constructors contain invalid constructor chaining calls. At line n1, this() attempts to invoke a no-argument constructor, but none is defined in the class - the compiler has no Person() to delegate to. At line n2, Person(name) is simply not valid Java syntax for constructor chaining; constructors cannot be called using the class name like a regular method - the correct syntax would be this(name), and it must appear as the first statement.
Options B and C are wrong because they each blame only one line, when in fact both constructors are broken for different reasons - n1 references a nonexistent no-arg constructor, and n2 uses illegal call syntax. Option A is wrong because the code never compiles in the first place, so no output is ever produced (and show() would also fail since number is undefined).
Memory tip: In Java, the only legal ways to chain constructors are this(...) (same class) and super(...) (parent class) - always as the first line of the constructor body. Any other form, including calling ClassName(...) directly, is a compile error.
Topics
Community Discussion
No community discussion yet for this question.