Bird
0
0

What will be the output of the following code?

medium📝 Predict Output Q4 of 15
Java - Constructors
What will be the output of the following code?
class A {
  A() { System.out.print("A"); }
}
class B extends A {
  B() { System.out.print("B"); }
}
public class Test {
  public static void main(String[] args) {
    new B();
  }
}
ABA
BAB
CA B
DB
Step-by-Step Solution
Solution:
  1. Step 1: Trace constructor calls

    Creating new B() calls B's constructor, which implicitly calls A's constructor first.
  2. Step 2: Output sequence

    A's constructor prints "A" first, then B's constructor prints "B" immediately after.
  3. Final Answer:

    AB -> Option B
  4. Quick Check:

    Superclass constructor runs before subclass = AB [OK]
Quick Trick: Superclass constructor output appears before subclass output [OK]
Common Mistakes:
  • Assuming subclass prints first
  • Expecting spaces between outputs
  • Ignoring implicit super() call

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes