Writing Constructors for Subclasses

AP Computer Science A· difficulty 4/5

public class A {
    public A() { System.out.print("A "); show(); }
    public void show() { System.out.print("A.show "); }
}
public class B extends A {
    private int x = 5;
    public void show() { System.out.print("B.show " + x + " "); }
}
new B();

What is printed?

  • A

    A B.show 0

    check_circle
  • B

    A B.show 5

  • C

    A A.show

  • D

    B.show 5 A

Explanation

Construction order: A's constructor runs first; show() dynamically dispatches to B.show, but B's field initializer hasn't run yet, so x is still 0.

Want 10 more like this — adaptive to your weak spots?

Related questions