Creating Superclasses and Subclasses

AP Computer Science A· difficulty 3/5

public class Parent {
    private int secret = 99;
    public int getSecret() { return secret; }
}
public class Child extends Parent {
    public int doubleSecret() {
        // attempt to access secret directly:
        return secret * 2;
    }
}

What is the result of compiling Child?

  • A

    Compile error: secret has private access in Parent

    check_circle
  • B

    Compiles fine; doubleSecret returns 198

  • C

    Compiles fine; doubleSecret returns 0

  • D

    Runtime error when called

Explanation

Private fields are not accessible in subclasses. Child must use the public accessor getSecret() rather than direct access.

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

Related questions