nerdexam
Oracle

1Z0-819 · Question #147

Given: class ConSuper { protected ConSuper() { this(2); } System.out.print("1"); } protected ConSuper(int a) { System.out.print(a); } } and public class ConSub extends ConSuper{ ConSub(){ this(4)…

The correct answer is B. 2143. Option B is correct assuming the main method calls new ConSub() (the no-arg version) - there appears to be a typo in the transcription. Tracing the call chain: ConSub() immediately delegates via this(4) to ConSub(int a), which triggers an implicit super() call to ConSuper()…

Java Object-Oriented Approach

Question

Given: class ConSuper { protected ConSuper() { this(2); } System.out.print("1"); } protected ConSuper(int a) { System.out.print(a); } } and public class ConSub extends ConSuper{ ConSub(){ this(4); System.out.print("3"); } ConSub(int a) { System.out.print(a); } public static void main (String[] args){ new ConSub(4); } } What is the result?

Options

  • A3134
  • B2143
  • C214
  • D244

How the community answered

(35 responses)
  • A
    11% (4)
  • B
    80% (28)
  • C
    3% (1)
  • D
    6% (2)

Explanation

Option B is correct assuming the main method calls new ConSub() (the no-arg version) - there appears to be a typo in the transcription. Tracing the call chain: ConSub() immediately delegates via this(4) to ConSub(int a), which triggers an implicit super() call to ConSuper(), which in turn delegates via this(2) to ConSuper(int a) - printing "2"; unwinding back to ConSuper() prints "1"; unwinding back to ConSub(int a) prints "4"; finally unwinding back to ConSub() prints "3" - giving 2143.

Why distractors are wrong:

  • A (3134): Would require ConSub()'s print("3") to execute before delegation via this(), but this() must be the first statement and blocks anything after it until the chain unwinds.
  • C (214): This is actually the output if main calls new ConSub(4) directly - it skips ConSub() entirely, so the "3" is never printed.
  • D (244): No execution path produces two 4s; this confuses the 4 passed into ConSub(int a) with something printed by ConSuper.

Memory tip: Think of this() and super() constructor chaining as a stack - execution dives all the way down to the innermost constructor before any print statements run on the way back up, so read the output bottom-up through the call chain.

Topics

#constructor chaining#this() and super() calls#inheritance#execution order

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice