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()…
Question
Options
- A3134
- B2143
- C214
- D244
How the community answered
(35 responses)- A11% (4)
- B80% (28)
- C3% (1)
- D6% (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()'sprint("3")to execute before delegation viathis(), butthis()must be the first statement and blocks anything after it until the chain unwinds. - C (214): This is actually the output if
maincallsnew ConSub(4)directly - it skipsConSub()entirely, so the"3"is never printed. - D (244): No execution path produces two
4s; this confuses the4passed intoConSub(int a)with something printed byConSuper.
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
Community Discussion
No community discussion yet for this question.