Bird
0
0

What will be the output of this code?

medium📝 Predict Output Q4 of 15
Java - Inheritance
What will be the output of this code?
class Demo {
  Demo() {
    this(10);
    System.out.println("No-arg constructor");
  }
  Demo(int x) {
    System.out.println("Param constructor: " + x);
  }
  public static void main(String[] args) {
    new Demo();
  }
}
AParam constructor: 10 No-arg constructor
BNo-arg constructor Param constructor: 10
CParam constructor: 10
DNo-arg constructor
Step-by-Step Solution
Solution:
  1. Step 1: Trace constructor calls

    The no-argument constructor calls this(10), so the parameterized constructor runs first printing "Param constructor: 10".
  2. Step 2: Continue execution after chaining

    After the parameterized constructor finishes, control returns to the no-arg constructor which prints "No-arg constructor".
  3. Final Answer:

    Param constructor: 10 No-arg constructor -> Option A
  4. Quick Check:

    Constructor chaining calls param constructor first [OK]
Quick Trick: Chained constructor runs before current constructor body [OK]
Common Mistakes:
  • Assuming no-arg constructor prints first
  • Ignoring chaining order
  • Expecting only one print statement

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes