Unit 4: Classes & Objects
Classes define blueprints. Objects are individual instances with their own data. AP class-design FRQs commonly ask for constructors, fields, mutators, accessors, and boundary logic.
classobjectconstructorprivategettersettertoString
Core Examples
Basic Class
public class Book {
private String title;
private int pagesRead;
public Book(String t) {
title = t;
pagesRead = 0;
}
}Private instance variables protect object state.
Accessor and Mutator
public int getPagesRead() {
return pagesRead;
}
public void read(int pages) {
pagesRead += pages;
}Methods control how data changes.
Reference Variables
Book a = new Book("Hobbit");
Book b = a;
b.read(10);Both variables can refer to the same object.
Try It in Java
Run and modify the examples below. Add print statements, change values, and test edge cases.
Code Tracing Drop-Down Practice
If b = a and b changes the object, what does a see?
The same change.
Why use private fields?
Encapsulation prevents uncontrolled data changes.
What does a constructor do?
It initializes a new object.
Debugging Practice
Bug: accessing a private field from another class.
Use a public getter or method.
Bug: constructor has a return type.
Constructors have no return type.
AP-Style Multiple Choice
Which line creates an object?
Book b = new Book("Hobbit");
What method returns a readable summary?
toString()
What is stored in an object variable?
A reference.
FRQ Practice
Write a Stopwatch class with private seconds and running fields. Include a constructor, start(), stop(), tick(), getSeconds(), and toString().Scoring focus
Look for the correct method signature, correct data use, clear control flow, and boundary-case handling.
Physics / Real-World Mini Project
Create a Particle class with mass, position, and velocity. Include methods to update position and calculate kinetic energy.