Writing Constructors for Subclasses

AP Computer Science A· difficulty 3/5

public class A {
    public A(int x) { System.out.print("A" + x + " "); }
}
public class B extends A {
    public B(int x) {
        System.out.print("B" + x + " ");
        super(x);
    }
}

What occurs?

  • A

    Prints 'B1 A1 '

  • B

    Prints 'A1 B1 '

  • C

    Compile error: super(...) must be the first statement

    check_circle
  • D

    Runtime error

Explanation

super(...) calls must be the first statement in a constructor. Otherwise, the compiler reports an error.

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

Related questions