AP CSA Unit 3 | Classes, Objects, and Built-in Classes

Story-driven practice with blueprints, objects, constructors, getters, setters, encapsulation, Strings, Math, wrappers, object references, null, toString, and a projectile object mini-project.

Unit 3 Big Idea: Objects Represent Real Things

A class is a design for a kind of thing. An object is one actual thing built from that design. This unit moves students from writing isolated statements and control structures into building small software models.

classesobjectsconstructorsprivate fieldsgetterssettersStringMathIntegerDoublereferencesnulltoString

AP habit: Every object question comes down to three questions: What object exists? What data does it store? Which method changes or returns that data?

Why Classes Exist

Without classes, related information gets scattered across separate variables. That becomes ugly fast.

Loose Data

String athlete1Name = "Sarah";
int athlete1Grade = 11;
double athlete1PR = 5.23;

String athlete2Name = "Emma";
int athlete2Grade = 12;
double athlete2PR = 5.01;

Object Data

Athlete a = new Athlete("Sarah", 11, 5.23);
Athlete b = new Athlete("Emma", 12, 5.01);
Story: Think of a coach's roster. A roster is not just names in one pile, grades in another pile, and PRs in another pile. Each athlete has one profile that holds the information together.

1. Classes as Blueprints

A class is a blueprint. It describes the data and behavior every object of that type should have.

public class Athlete {
    private String name;
    private int grade;
    private double pr1600;
}
Analogy: A blueprint is not a house. A class is not an object. The blueprint tells the builder what a house should contain; the class tells Java what an object should contain.
Java TermAnalogyMeaning
ClassBlueprintThe design or template.
ObjectBuilt houseOne actual instance created from the class.
Instance variableRooms and featuresThe data each object stores.

2. Constructors: Creating Objects

A constructor initializes an object when it is created.

public class Athlete {
    private String name;
    private int grade;
    private double pr1600;

    public Athlete(String n, int g, double pr) {
        name = n;
        grade = g;
        pr1600 = pr;
    }
}
Analogy: The constructor is the object's birth certificate. When a new athlete profile is created, the constructor records the starting name, grade, and PR.
How many objects are created here?
Athlete a = new Athlete("Sarah", 11, 5.23);
Athlete b = new Athlete("Emma", 12, 5.01);

Two. The keyword new creates a new object each time.

3. Getters and Setters

Because AP CSA expects instance variables to be private, outside code should usually read and change them through public methods.

Getter: A Window

public double getPR() {
    return pr1600;
}

A getter lets other code look at private data without changing it.

Setter: A Controlled Doorway

public void setPR(double newPR) {
    if (newPR > 0) {
        pr1600 = newPR;
    }
}

A setter lets other code request a change, but the class can validate the change first.

Analogy: A getter is a window into a records office. You can see information. A setter is the front desk. You can request a change, but the office checks whether the request is valid.

4. Encapsulation: Protecting Object Data

Encapsulation means keeping data private and allowing access through controlled public methods.

Bad Access

Athlete a = new Athlete("Sarah", 11, 5.23);
a.pr1600 = -100;  // not allowed if pr1600 is private

Controlled Access

Athlete a = new Athlete("Sarah", 11, 5.23);
a.setPR(5.10);    // allowed if method is public
AP phrase to know: private instance variables plus public methods is the standard AP CSA pattern for class design.

5. Methods: Object Behaviors

Methods describe what an object can do or calculate. Some methods change the object. Some return information. Some do both.

public boolean isStateQualifier(double standard) {
    return pr1600 <= standard;
}

public void improvePR(double seconds) {
    if (seconds > 0) {
        pr1600 -= seconds;
    }
}
Analogy: An athlete profile can answer questions like “Are you qualified?” and can update itself after a new race result.
What is the difference between void and a return type?

A void method performs an action and does not send back a value. A non-void method must return a value of the declared type.

6. Built-in AP Java Classes

Students do not write every class from scratch. The AP Java subset expects them to use several built-in classes confidently.

String: Digital Sentence

String stores text. Its methods are editing tools.

String word = "computer";
System.out.println(word.length());      // ruler
System.out.println(word.substring(1,4)); // scissors
System.out.println(word.indexOf("p"));   // search tool
System.out.println(word.equals("java")); // exact comparison

Math: Calculator Toolbox

Math methods are static, so they are called with the class name.

double speed = Math.sqrt(49);
double area = Math.PI * Math.pow(3, 2);
int distance = Math.abs(-12);
int die = (int)(Math.random() * 6) + 1;

Wrapper Classes: Folders for Primitives

Integer and Double wrap primitive values as objects.

Integer points = 42;
Double time = 12.84;

ArrayList<Integer> scores = new ArrayList<Integer>();
scores.add(points);

ArrayList Preview: Expandable Filing Cabinet

An ArrayList grows and shrinks as items are added or removed.

ArrayList<String> events = new ArrayList<String>();
events.add("1600m");
events.add("800m");
System.out.println(events.get(0));
System.out.println(events.size());
Note: ArrayLists and inheritance get full pages later. Unit 3 only introduces why wrappers and built-in classes matter.

7. Object References: The Most Important AP Trap

Primitive variables store values. Object variables store references to objects. Two reference variables can point to the same object.

Athlete a = new Athlete("Sarah", 11, 5.23);
Athlete b = a;

b.setName("Emma");

System.out.println(a.getName());
What prints, and why?

Emma prints. a and b refer to the same object. The code did not create a second Athlete object. It created a second reference to the first object.

Analogy: Two coaches can hold copies of the same map to the same locker. Changing what is inside the locker affects what both coaches see.

8. Null References: Empty Parking Spaces

null means a reference variable does not currently refer to any object.

Athlete a = null;
// a.getName();  // NullPointerException
Analogy: A parking space label can exist even when there is no car in the space. Calling a method on null is like trying to drive a car that is not there.
Why does AP CSA care about null?

AP questions often ask what happens when code tries to call a method on a null reference. The result is a runtime error, not a normal value.

9. toString(): The Object's ID Card

A toString method returns a readable summary of an object. This is especially useful in projects, debugging, and ArrayLists.

public String toString() {
    return name + " grade " + grade + " PR: " + pr1600;
}
Analogy: toString() is the object's ID card. It gives a quick readable summary instead of forcing someone to inspect every field separately.

10. Inheritance Preview: Family Trees

Inheritance is taught in depth later, but students should understand the idea now: some classes are more specific versions of other classes.

Athlete
  |
  |-- Runner
  |-- Jumper
  |-- Thrower
public class Runner extends Athlete {
    private double weeklyMileage;
}
Preview only: In the inheritance unit, students will learn extends, super(), overriding, and polymorphism.

Try It in Java

Use the online IDE below to run, modify, and break the examples. Require students to add one new field, one getter, one setter, and one method.

Physics Connection: Projectile Object Mini-Project

This mini-project connects object-oriented design to physics simulation. Students build a Projectile class that stores launch data and calculates range and time of flight.

public class Projectile {
    private double speed;
    private double angleDegrees;

    public Projectile(double s, double a) {
        speed = s;
        angleDegrees = a;
    }

    public double getSpeed() {
        return speed;
    }

    public void setSpeed(double s) {
        if (s > 0) {
            speed = s;
        }
    }

    public double calculateRange() {
        double g = 9.8;
        double angleRadians = angleDegrees * Math.PI / 180.0;
        return speed * speed * Math.sin(2 * angleRadians) / g;
    }

    public double calculateTime() {
        double g = 9.8;
        double angleRadians = angleDegrees * Math.PI / 180.0;
        return 2 * speed * Math.sin(angleRadians) / g;
    }

    public String toString() {
        return "Projectile: speed=" + speed + " m/s, angle=" + angleDegrees + " degrees";
    }
}

Driver Program

public class Main {
    public static void main(String[] args) {
        Projectile p = new Projectile(20, 45);
        System.out.println(p);
        System.out.println("Range: " + p.calculateRange());
        System.out.println("Time: " + p.calculateTime());
    }
}

Required Modification

Add a getter and setter for angleDegrees. The setter should only allow values from 0 to 90.

Extension

Add a method getMaxHeight(). Use vertical velocity and kinematics.

Challenge

Create several Projectile objects and compare which one travels farthest.

AP Code Tracing Challenges

1. Object creation: how many Athlete objects exist?
Athlete a = new Athlete("Mia", 10, 6.12);
Athlete b = new Athlete("Noah", 11, 5.44);
Athlete c = b;

Two objects exist. c is another reference to the same object as b.

2. String tracing: what prints?
String s = "training";
System.out.println(s.substring(1, 5));

rain. The substring includes index 1 and stops before index 5.

3. Math.random: what values are possible?
int x = (int)(Math.random() * 4) + 3;

Possible values are 3, 4, 5, and 6.

4. Setter validation: what is the final speed?
Projectile p = new Projectile(20, 45);
p.setSpeed(-10);
System.out.println(p.getSpeed());

20.0, assuming the setter only changes speed when the new speed is positive.

Common Unit 3 Mistakes

Forgetting private

AP-style class design should use private instance variables.

Constructor Return Type

Constructors do not have return types, not even void.

Using == with Strings

Use .equals() to compare text contents.

Confusing Object Copy with Reference Copy

b = a; does not create a new object.

Calling Methods on null

This causes a runtime error.

Forgetting to Return

Every path in a non-void method must return the declared type.

AP-Style Multiple Choice Practice

Which keyword protects instance variables from direct outside access?

private.

Which method is most appropriate for reading the value of a private variable?

An accessor method, also called a getter.

Which method is most appropriate for safely changing a private variable?

A mutator method, also called a setter.

Which method should compare two String contents?

equals.

Why are wrapper classes needed with ArrayLists?

ArrayLists store objects, not primitive values. Use Integer for int and Double for double.

FRQ Practice: Athlete Class

Write a class Athlete with private instance variables name, grade, and pr1600.

Scoring Guide
CriteriaPoints
Private instance variables declared correctly2
Constructor initializes all fields2
Accessors return correct values2
Mutator validates new PR correctly2
Qualifier and toString methods correct2

Teacher Notes: How to Use This Page