Bird
0
0

Given the class below, what will be the output when new Box(); is executed?

hard📝 Application Q15 of 15
Java - Inheritance
Given the class below, what will be the output when new Box(); is executed?
class Box {
  Box() {
    this(3, 4);
    System.out.print("X");
  }
  Box(int w, int h) {
    this(w, h, 5);
    System.out.print("Y");
  }
  Box(int w, int h, int d) {
    System.out.print("Z");
  }
}
AZXY
BZY
CXYZ
DZYX
Step-by-Step Solution
Solution:
  1. Step 1: Trace constructor chaining calls

    Calling new Box() calls no-arg constructor, which calls Box(int w, int h), which calls Box(int w, int h, int d).
  2. Step 2: Track printed characters in order

    The deepest constructor prints "Z" first, then returns to middle constructor which prints "Y", then returns to no-arg constructor which prints "X".
  3. Final Answer:

    ZYX -> Option D
  4. Quick Check:

    Chained constructors print Z then Y then X [OK]
Quick Trick: Deepest constructor prints first, then unwind chain [OK]
Common Mistakes:
  • Assuming outer constructor prints first
  • Ignoring chaining order
  • Mixing up print order in nested calls

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes