Creating Superclasses and Subclasses

AP Computer Science A· difficulty 3/5

public class A {
    private int x = 5;
}
public class B extends A {
    public int getX() { return x; }
}

What is true about class B?

  • A

    Compile-time error: x has private access in A

    check_circle
  • B

    Compiles and returns 5

  • C

    Compiles but returns 0

  • D

    Runtime error

Explanation

<code>private</code> fields are not accessible to subclasses. To allow subclass access, the field must be <code>protected</code> (or use an accessor method).

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

Related questions