Writing Constructors for Subclasses

AP Computer Science A· difficulty 4/5

A B extends A C extends B

Given the hierarchy in the figure and:

<code class="language-java">class A { public A() { System.out.print("A "); } } class B extends A { public B() { System.out.print("B "); } } class C extends B { public C() { System.out.print("C "); } public C(int x) { System.out.print("C" + x + " "); } } new C(7); </code></pre> What is printed?

  • A

    A B C7

    check_circle
  • B

    A B C C7

  • C

    C7 B A

  • D

    C7

Explanation

Each constructor implicitly calls <code>super()</code> first. So <code>C(int)</code> calls <code>B()</code>, which calls <code>A()</code>. A prints first, then B, then "C7" from the chosen <code>C(int)</code> constructor.

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

Related questions