AP Computer Science A · Topic 5.1
Anatomy of a Class Practice
Part of Writing Classes.
Practice questions
5
Sample questions
5 of 5 — sign in to practice the rest with adaptive difficulty and mastery tracking.
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?
- Acheck_circle
To enforce encapsulation; outside code must use methods that validate access and modification
- 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.
- A
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?
- Acheck_circle
50
- 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.
- A
Sample 3difficulty 2/5
Which is the correct minimal class declaration?
- A
Dog class { }
- B
public Dog { }
- Ccheck_circle
class Dog { }
- D
class { Dog }
Why
<code>class ClassName { }</code> defines an empty class. <code>public</code> is optional but common.
- A
Sample 4difficulty 2/5
An instance variable is declared
- Acheck_circle
Inside the class body, outside methods
- B
Inside a method
- C
Outside the class file
- D
As a parameter
Why
Instance fields belong to each object; declared at class level.
- A
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
- Ccheck_circle
Two distinct objects with their own state
- D
The same object
Why
Each <code>new</code> creates a fresh object.
- A