AP Computer Science A · Topic 5.1

Anatomy of a Class Practice

Part of Writing Classes.

Practice questions

5

Want a predicted score for the whole AP CSA exam? Take the 20-question diagnostic and Lumi will plan the rest.

Sample questions

5 of 5 — sign in to practice the rest with adaptive difficulty and mastery tracking.

  1. Sample 1difficulty 1/5

    public class Account {
        private double balance;
        public double getBalance() { return balance; }
        public void deposit(double amt) {
            if (amt > 0) balance += amt;
        }
    }
    // ...

    Which best describes why balance is private?

    • A

      To enforce encapsulation; outside code must use methods that validate access and modification

      check_circle
    • B

      Because private variables run faster

    • C

      So they cannot be initialized

    • D

      So static methods cannot use them

    Why

    Encapsulation hides internal state and exposes a controlled interface, allowing validation logic in the methods.

  2. Sample 2difficulty 2/5

    public class Box {
        private final int CAPACITY;
        public Box(int c) { CAPACITY = c; }
        public int getCap() { return CAPACITY; }
    }
    // ...
    Box b = new Box(50);
    System.out.println(b.getCap());

    What is printed?

    • A

      50

      check_circle
    • B

      Compile-time error: cannot assign final

    • C

      0

    • D

      null

    Why

    A blank final instance variable can be assigned exactly once in the constructor; this is allowed.

  3. Sample 3difficulty 2/5

    Which is the correct minimal class declaration?

    • A

      Dog class { }

    • B

      public Dog { }

    • C

      class Dog { }

      check_circle
    • D

      class { Dog }

    Why

    <code>class ClassName { }</code> defines an empty class. <code>public</code> is optional but common.

  4. Sample 4difficulty 2/5

    An instance variable is declared

    • A

      Inside the class body, outside methods

      check_circle
    • B

      Inside a method

    • C

      Outside the class file

    • D

      As a parameter

    Why

    Instance fields belong to each object; declared at class level.

  5. Sample 5difficulty 3/5

    <code>Dog a = new Dog(); Dog b = new Dog();</code> — a and b are

    • A

      Compile error

    • B

      References to null

    • C

      Two distinct objects with their own state

      check_circle
    • D

      The same object

    Why

    Each <code>new</code> creates a fresh object.