3.03 Anatomy of a Class

16 min read • Assignment

1. LxD Cycle Process

Empathize: Students often copy public and private as boilerplate without asking who is allowed to touch the data, so they make everything public and the class stops protecting its own state.

Define:

  • POV: CSA students need to treat public and private as decisions about who may use a class’s data, because a class that lets any code change its fields cannot keep its own state valid.
  • Learning Goal: Students will label the parts of a class (instance variables, constructor, methods), declare instance variables private and the constructor and outside-facing methods public, and explain why each object has its own copy of every instance variable.

Ideate:

  • HMW Question: How might we get students to ask “who should be allowed to change this?” before they type public?
  • HMW Question: How might we show that the compiler, not the programmer, is what enforces private?
  • Activity: Read and run a Player class, break it with a private-access error, check your understanding in the MCQ, then build a Pet class and a Book class.

Prototype & Test: Lesson authors: add what happened in your trial run and what you changed.


2. Lesson Plan

Learning Objective: Identify the parts of a class and use public and private to control which code can reach each one.

Success Criteria: You can label the instance variables, constructor, and methods in a class, mark instance variables private and the constructor public, and explain why p.wins fails to compile when it is written in a different class.

Tech Talk (5 minutes)

A class is a blueprint. An object is one thing built from it with new. Every class is made from the same three kinds of parts:

Code Runner Challenge

Run it, then change how many times each player wins and predict the new output

View IPYNB Source
public class Player {                  // class header: public, the keyword class, a name
    private String gamertag;           // instance variables: the data each object holds
    private int wins;

    public Player(String gamertag) {   // constructor: same name as the class, no return type
        this.gamertag = gamertag;
        this.wins = 0;
    }

    public int getWins() {             // method: a behavior other code can ask for
        return wins;
    }

    public static void main(String[] args) {
        Player p = new Player("Nova");
        System.out.println(p.getWins());
    }
}
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

What the runner is doing: it sends this code to a Java compiler, then runs main. main builds one Player and prints its win count, so you should see 0. Only main starts on its own. The constructor and getWins() run because main calls them.

The keywords public and private decide who can reach each part. That is encapsulation: the details stay inside the class, and outside code goes through its public methods.

Code Runner Challenge

Run it and read the compiler error, then comment out the line that reaches into combo and run it again

View IPYNB Source
public class AccessDemo {
    public static void main(String[] args) {
        Player p = new Player("Nova");
        System.out.println(p.getWins());     // 0, allowed: getWins() is public
        // System.out.println(p.wins);       // remove the // and run it: wins is private to Player
    }
}

class Player {
    private String gamertag;
    private int wins;

    public Player(String gamertag) {
        this.gamertag = gamertag;
        this.wins = 0;
    }

    public int getWins() {
        return wins;
    }
}
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

What the runner is doing: the same two steps, compile and then run. It prints 0 because getWins() is public. Now remove the // in front of the last line in main and run again. The compile step fails, so main never runs and you get an error instead of 0.

Every object gets its own copy of each instance variable, so new Player("Nova") and new Player("Ace") never share a win count.

From the College Board

AP CSA Unit 3, Topic 3.3 Anatomy of a Class. Quoted from the course and exam description (College Board, 2025, p. 83):

  • 3.3.A.1 “Data encapsulation is a technique in which the implementation details of a class are kept hidden from external classes. The keywords public and private affect the access of classes, data, constructors, and methods. The keyword private restricts access to the declaring class, while the keyword public allows access from classes outside the declaring class.”
  • 3.3.A.4 “Instance variables belong to the object, and each object has its own copy of the variable.”
  • 3.3.A.5 “Access to attributes should be kept internal to the class in order to accomplish encapsulation. Therefore, it is good programming practice to designate the instance variables for these attributes as private unless the class specification states otherwise.”

The same page also says that in this course classes are always designated public (3.3.A.2) and constructors are always designated public (3.3.A.3).


3. Reference Guide

Key Vocabulary


Term Definition Example
Class Blueprint that describes an object’s data and behavior. public class Player
Object One instance built from a class with new. new Player("Nova")
Instance variable Data that each object holds its own copy of. private int wins;
Constructor Sets up a new object. Same name as the class, no return type. public Player(String g)
Method A named behavior the object can perform. public void recordWin()
Encapsulation Hiding a class’s details behind its public methods. private field + public getter
public Code outside the class may use it. public int getWins()
private Only code inside the declaring class may use it. private int wins;
  • Instance variables describe what an object has
  • Methods describe what an object does

Parts of a Class

Part Usually declared Job
Class header public Names the class
Instance variables private Store each object’s state
Constructor public Gives a new object its starting values
Accessor method (getter) public Lets outside code read a private value
Mutator method public Lets outside code change a private value in a controlled way
Helper method private Work the class does for itself

Picking an Access Level

  • Instance variables → private
  • Constructors → public
  • Methods other classes need to call → public
  • Helper methods only this class uses → private

How the Code Runner Works

Each Code Runner box on this page is a small Java compiler and runner. When you press Run:

  1. Send. The page sends the code in the editor to the Java runner on the course server.
  2. Check. The server refuses code that contains blocked words such as File, Thread, sleep, or socket, even inside a comment or inside a longer word like profile. You get a “forbidden operation” message instead of a run.
  3. Find the class. It takes the first public class in your code and saves it as ClassName.java. That class needs a main method, because main is where a Java program starts.
  4. Compile. javac turns your code into bytecode. If the code breaks a rule, such as reaching a private field from another class, you get Compilation error: with the message, and the program does not run.
  5. Run. If it compiled, the runner calls main. Anything printed with System.out.println shows up in the Output panel. A program that runs longer than 3 seconds is stopped.

Edit the code and press Run as often as you like. Every run starts from scratch, so nothing is remembered from the last one. Leave the language dropdown on Java.

The ClassName.main(null); line at the bottom of a notebook cell is for Jupyter. The site runner leaves it out and calls main for you.


4. Code Examples

A. Simple: Parts of a Class

Two Player objects are built from one class. Each keeps its own wins.

Code Runner Challenge

Replace the sample values with your own, then run it

View IPYNB Source
// CODE_RUNNER: Run it, then change how many times each player wins and predict the new output
// Anatomy of a class: the parts of Player
public class Player {
    // Instance variables: private, and every object gets its own copy
    private String gamertag;
    private int wins;

    // Constructor: public, same name as the class, no return type
    public Player(String gamertag) {
        this.gamertag = gamertag;
        this.wins = 0;
    }

    // Public methods: the way outside code reads or changes the data
    public String getGamertag() {
        return gamertag;
    }

    public int getWins() {
        return wins;
    }

    public void recordWin() {
        wins++;
    }

    public static void main(String[] args) {
        Player a = new Player("ShadowStrike");
        Player b = new Player("NovaQueen");

        a.recordWin();
        a.recordWin();
        b.recordWin();

        System.out.println(a.getGamertag() + ": " + a.getWins() + " wins");
        System.out.println(b.getGamertag() + ": " + b.getWins() + " wins");
    }
}

Player.main(null);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

What the runner is doing:

  1. Compiles Player. The private fields are only used inside Player, so it compiles.
  2. Calls main. main makes two objects with new, which runs the constructor once for each.
  3. a.recordWin() runs twice and b.recordWin() runs once. Each call changes only the object it was called on, because wins belongs to the object.
  4. The two println lines read the data back through the public getters, so you see ShadowStrike: 2 wins and NovaQueen: 1 wins.

Try it: change how many times each player wins and predict the output before you press Run.

B. Complex: Public vs Private

private is enforced by the compiler. Outside code can call a public method, but it cannot reach a private field or call a private method.

Code Runner Challenge

Fill in the blanks, then run it

View IPYNB Source
// CODE_RUNNER: Run it and read the compiler error, then comment out the line that reaches into combo and run it again
// Public vs private access
public class LockerDemo {
    public static void main(String[] args) {
        Locker locker = new Locker(1234);
        System.out.println(locker.open(1234));   // public method: allowed
        System.out.println(locker.combo);        // private field: compile error
    }
}

// Only one class in this cell can be public, so Locker has no modifier here.
// In this course, a class is always declared public.
class Locker {
    private int combo;

    public Locker(int combo) {
        this.combo = combo;
    }

    public boolean open(int guess) {
        return matches(guess);
    }

    private boolean matches(int guess) {   // private helper: only Locker can call it
        return guess == combo;
    }
}

LockerDemo.main(null);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

What the runner is doing:

  1. Compiles LockerDemo and Locker together, because they are in the same code box.
  2. The first println is fine, because open is public. The second one breaks the rules: combo is private, so the compiler stops with combo has private access in Locker.
  3. Because the compile step failed, the run step never happens. You do not see the true from the first println, even though that line was fine.
  4. Comment out the line that reaches into combo and run again. Now it compiles, and main prints true. open can use matches for you because matches is private, and code inside Locker is allowed to call it.

5. Hacks & Practice Tasks

Prepare your submission IPYNB

  1. Create a new notebook in your portfolio homework area: _notebooks/homework.
  2. Add one raw cell at the top with the frontmatter:
---
layout: post
codemirror: true
title: Anatomy of a Class HW
categories: [Java]
lesson_language: Java
lesson_topic: Anatomy-of-a-Class HW
lesson_part: interactive
lesson_type: lesson
permalink: /csa/unit_03/3_3-hw
author: yourGithubID
---
  1. Add code cells for the Popcorn Hack and the Homework Hack. Make sure every cell runs with visible output.
  2. Submit the link to your published page at the bottom of this page, and paste this in the description box:
Lesson: CSA 3.3 Anatomy of a Class
MCQ 3.3: <paste the copied result line, such as 7/9 | answers: B,D,A,C,C,D,A,B,C>
Popcorn: Pet class with private name and age, public constructor, public getName() and birthday(), private helper, runs and prints
Homework: all three Book fields private (yes/no)
Homework: constructor sets title, totalPages, and pagesRead = 0 (yes/no)
Homework: pages read after readPages(500) = <value>
Homework: status before and after finishing = <s1>, <s2>

Submission Safety Rules (Read First)

  • One class per cell, ending with ClassName.main(null);.
  • Run each cell and leave the output showing.
  • Use your own values, not the sample answer.
  • Include your MCQ score.
  • Use ## headings or smaller.

Popcorn Hack (In-Class)

2-minute challenge: build a small Pet class, then run the cell.

  1. A private instance variable for the pet’s name (text)
  2. A private instance variable for its age (whole number)
  3. A public constructor that sets both
  4. A public method that returns the name
  5. A public method that changes the age (a birthday)
  6. A helper method that only the class itself calls (which keyword keeps outside code from calling it?)

Replace the sample values with your own. The cell below is for reading: copy it into a code cell in your submission notebook and run it there.

// CODE_RUNNER: Replace the sample values with your own, then run it
// Practice #1 - Try it yourself first!
public class Pet {
    // Sample answer:
    private String name;
    private int age;

    public Pet(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void birthday() {
        age++;
    }

    private String stage() {        // helper: only Pet calls it
        if (age < 2) {
            return "young";
        }
        return "grown";
    }

    public String describe() {
        return name + " is " + age + " and " + stage();
    }

    public static void main(String[] args) {
        Pet pet = new Pet("Biscuit", 1);
        pet.birthday();
        System.out.println(pet.getName());
        System.out.println(pet.describe());
    }
}

Pet.main(null);

6. MCQ Check

9 questions, one at a time. Answer, check, then go to the next one. At the end, copy the score line into your submission notes.

Homework Hack

Task: Build a Book class. Make every instance variable private, set them in a public constructor, add public methods to read and update the pages, and use a private helper that the class calls for itself.

Solution Skeleton:

// CODE_RUNNER: Fill in the blanks, then run it
public class Book {
    // 1. Make all three instance variables private
    String title;
    int totalPages;
    int pagesRead;

    // 2. Make this constructor public: set title and totalPages, and start pagesRead at 0
    Book(String title, int totalPages) {
    }

    // 3. Return how many pages have been read
    public int getPagesRead() {
        return -1;
    }

    // 4. Add pages, but never let pagesRead go past totalPages
    public void readPages(int pages) {
    }

    // 5. Make this helper private: true when every page has been read
    boolean isFinished() {
        return false;
    }

    // 6. Use isFinished() to return "Finished" or "Reading"
    public String getStatus() {
        return "?";
    }

    public static void main(String[] args) {
        Book book = new Book("Dune", 412);
        book.readPages(100);
        System.out.println(book.getStatus());      // Reading
        book.readPages(500);
        System.out.println(book.getPagesRead());   // 412
        System.out.println(book.getStatus());      // Finished
    }
}

Book.main(null);

7. Grading Plan (1 Point Total)

Part Points What earns the points
Popcorn 0.2 Pet has private name and age, a public constructor, public getName() and birthday(), and a private helper, and the cell runs.
MCQ 0.2 8 or 9 correct. 0.15 for 5 to 7 correct, 0.1 if every question was answered.
Homework: private fields 0.15 title, totalPages, and pagesRead are all private.
Homework: constructor 0.15 Public constructor sets title and totalPages, and pagesRead starts at 0.
Homework: reading pages 0.15 readPages(500) stops at 412 and getPagesRead() prints 412.
Homework: status 0.15 isFinished() is private, and getStatus() uses it to print Reading and then Finished.
Total 1.0  

Quick Validation Checklist

  • Each cell ends with ClassName.main(null); and shows output.
  • MCQ score in the notes.
  • Every instance variable is private, and every constructor and outside-facing method is public.
  • isFinished() and stage() are private helpers called from inside their own class.
  • Book prints Reading, 412, and Finished.

8. Lesson Revisions & Feedback Evidence

Feedback Received: Lesson authors: what your peers said in the practice run.

Revision Made: Lesson authors: what you changed because of it.


9. Academic References

College Board (Required)

The AP CSA Course and Exam Description defines the access-control rules this lesson is built on:

“Data encapsulation is a technique in which the implementation details of a class are kept hidden from external classes. The keywords public and private affect the access of classes, data, constructors, and methods. The keyword private restricts access to the declaring class, while the keyword public allows access from classes outside the declaring class.” (College Board, 2025, p. 83)

This lesson directly addresses Essential Knowledge statements 3.3.A.1 (public vs. private access), 3.3.A.4 (each object holds its own copy of every instance variable), and 3.3.A.5 (instance variables should be private unless stated otherwise).

APA Citation:

College Board. (2025). AP Computer Science A course and exam description [Effective fall 2025]. https://apcentral.collegeboard.org/media/pdf/ap-computer-science-a-course-and-exam-description-effective-fall-2025.pdf


Outside Academic Reference

Oracle’s official Java documentation explains why access modifiers exist and what each one controls:

“Access level modifiers determine whether other classes can use a particular field or invoke a particular method… private: The field or method is accessible only within its own class.” (Oracle, n.d.)

This connects directly to Example B above – Locker.combo and Locker.matches() are only reachable from inside Locker, which is exactly why locker.combo fails to compile from LockerDemo while locker.open(1234) succeeds.

APA Citation:

Oracle. (n.d.). Controlling access to members of a class. Oracle Java Tutorials. https://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

Submit Assignment

Click to upload or drag and drop
PDF, ZIP, images, documents, or Jupyter notebooks (.ipynb) (Max 10MB per file)

Need to update a submission later? Open the submissions dashboard.

Course Timeline