nerdexam
Oracle

1Z0-809 · Question #128

class Vehicle { int x; Vehicle() { this(10); // line n1 } Vehicle(int x) { this.x = x; } } class Car extends Vehicle { int y; Car() { super(); // line n2 this(20); } Car(int y) { this.y = y; }…

The correct answer is C. Compilation fails at line n2. Option C is correct because the Car() constructor illegally contains both super() and this(20) - Java only permits one explicit constructor call per constructor, and it must be the very first statement. Since super() already occupies that slot, the subsequent this(20) is a…

Question

class Vehicle { int x; Vehicle() { this(10); // line n1 } Vehicle(int x) { this.x = x; } } class Car extends Vehicle { int y; Car() { super(); // line n2 this(20); } Car(int y) { this.y = y; } public String toString() { return super.x + ":" + this.y; } } And given the code fragment: Vehicle v = new Car(); System.out.println(v); What is the result?

Options

  • A0:20
  • B10:20
  • CCompilation fails at line n2.
  • DCompilation fails at line n1.

How the community answered

(42 responses)
  • A
    7% (3)
  • B
    12% (5)
  • C
    76% (32)
  • D
    5% (2)

Explanation

Option C is correct because the Car() constructor illegally contains both super() and this(20) - Java only permits one explicit constructor call per constructor, and it must be the very first statement. Since super() already occupies that slot, the subsequent this(20) is a compile-time error; the compiler never reaches runtime.

Why the distractors are wrong:

  • A (0:20) and B (10:20) are both wrong because the program never compiles, so no output is produced at all.
  • D is wrong because line n1 - this(10) inside Vehicle() - is perfectly valid: it is the first (and only) statement, delegating to the Vehicle(int x) overload, which is standard constructor chaining.

Memory tip: Think of it as "one door in, one call out." Each constructor gets exactly one exit call - either super(...) or this(...), never both. If you spot a constructor with both, flag it as a compile error immediately.

Community Discussion

No community discussion yet for this question.

Full 1Z0-809 Practice