Writing Constructors for Subclasses

AP Computer Science A· difficulty 3/5

public class A {
    protected int x;
    public A() { x = 1; }
    public A(int v) { x = v; }
}
public class B extends A {
    public B() { super(5); }
}
// Usage:
B b = new B();
System.out.print(b.x);

What is printed?

  • A

    5

    check_circle
  • B

    1

  • C

    Compile error

  • D

    0

Explanation

super(5) calls A's parameterized constructor, setting x to 5.

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

Related questions