Unit 5: Writing Classes
AP Computer Science A: 11 practice questions with detailed explanations.
Unit Study Guide
Executive Summary
Classes are blueprints for objects. Instance variables store each object's state; methods define behavior; constructors set initial state.
Anatomy of a class
Instance variables (private) hold state. Constructors (same name as the class, no return type) initialize them. Methods have a return type or void, a name, and parameters. private members are visible only inside the class; public members are visible everywhere.
Methods and parameters
Formal parameters are the names in the signature; actual parameters are the values at the call. Primitives pass by value — changes inside the method do not affect the caller. Object references also pass by value, but the copy points to the same object, so its contents CAN change.
this and overloading
this refers to the current object and disambiguates instance variables from parameters. Overloading lets methods share a name when their parameter lists differ. Return type alone never distinguishes overloads.
Static members
static methods and variables belong to the class, not instances. Static methods cannot use instance variables directly and are called as ClassName.method(). Constants use public static final.
Exam traps
A missing return on one path fails to compile. Accessors return values; mutators change state. Getters/setters protect private fields (encapsulation).