Topic 3.3 — Anatomy of a Class

Goal: identify the key parts of a Java class (fields, constructors, methods), and explain how a class defines the data and behavior of its objects.

The big idea

A class is a blueprint for creating objects. It bundles data (fields/instance variables) and behavior (methods).

Objects created from the class each get their own copy of the instance variables.

What’s inside a class?

Part What it is Example
Fields store data (state) private int score;
Constructors initialize new objects public Student() { ... }
Methods actions the object can do public void addPoints(int p)

Example: a simple class

public class Counter {
  private int value;          // field (instance variable)

  public Counter() {          // constructor
    value = 0;
  }

  public void increment() {   // method
    value++;
  }

  public int getValue() {     // method
    return value;
  }
}

This shows the three main building blocks you’ll see constantly in AP CSA.

Fields (instance variables)

  • Store the object’s state (its “data”).
  • Usually marked private to protect the data.
  • Each object has its own copy.
private String name;
private int gradeLevel;

Constructors

  • Run automatically when you create an object with new.
  • Have the same name as the class.
  • No return type (not even void).
public Counter() {
  value = 0;
}

Methods

  • Define what an object can do.
  • Often interact with fields (read/update state).
  • Can return a value or be void.
public void increment() { value++; }
public int getValue() { return value; }

Common confusion: class vs object

Class Object
Blueprint/template One specific instance made from the class
Defines fields + methods Has actual stored field values
One class definition Many objects can be created

Quick self-check

  1. What are the three main parts of a class you should recognize?
  2. When does a constructor run?
  3. Why are fields often marked private?
  4. What’s the difference between a class and an object?
  5. In the example class, which method changes the object’s state?

← Back to Unit 3 topics