nerdexam
Oracle

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…

Working with Methods and Encapsulation

Question

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 Person(name); setAge(age); } //setter and getter methods go here public String show() { return name + " " + age + " " + number; } public static void main(String[] args) { Person p1 = new Person("Walter", 52); Person p2 = new Person("Jesse"); System.out.println(p1.show()); System.out.println(p2.show()); } } What is the result?

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)
  • A
    5% (2)
  • B
    16% (6)
  • C
    8% (3)
  • D
    70% (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

#constructor invocation#this() keyword#constructor chaining#compilation errors

Community Discussion

No community discussion yet for this question.

Full 1Z0-808 Practice