TOPIC 3.3 · STUDY
Anatomy of a Class
An AP CSA class opens with public class Name. Instance variables stay private by default. A constructor matches the class name and has no return type. Callers use public methods, which is how encapsulation exposes private data without making fields public. Each object keeps its own copy of those fields.
3.3.A
Anatomy of a class
A class is the blueprint for objects of one type. In AP CSA the class header is always public class followed by the class name. Headers such as private class, protected class, or a bare class with no access keyword are not used. Other code needs a public type so it can declare variables and construct objects of that class.
Inside the class you usually declare instance variables as private. That hides each object's data so outside code cannot assign the fields directly. A constructor has the same name as the class and no return type (not even void). Methods that client code should call are designated public. Encapsulation means private data is still usable, but only through those public methods. A private helper method may exist for the class to call itself; clients cannot call it. (Shared static members and the keyword this appear in later topics.)
public class Ticket {
private int seat;
public Ticket(int n) {
seat = n;
}
public int getSeat() {
return seat;
}
public void move(int n) {
seat = n;
}
}
Ticket is public, so other classes can use the type. seat is private, so a client cannot write t.seat = 5. The public constructor Ticket(int) and the public methods getSeat and move are the allowed ways to create a Ticket and work with its seat number. When two Ticket objects exist, each has its own seat; changing one object's seat does not change the other's.
A typical AP CSA class stacks a public header, private data, and public methods clients may call.
Key points
- Use public class Name; private, protected, and package-private class headers are not used.
- Instance variables are usually private unless a specification says otherwise.
- A constructor matches the class name and has no return type.
- Methods that callers use are public; private helpers stay inside the class.
- Encapsulation reaches private data through public methods, not by exposing fields.
- Each object has its own instance variables.
The class header is public class, not private class. Hiding a whole class is not the AP CSA form; hide the data with private fields instead.