← Back to course

Writing Classes

You’ll be able to

The anatomy of a class

A class typically has three parts: instance variables that hold each object’s data, a constructor that initializes a new object, and methods that define its behavior. In public class Dog { private int age; public Dog(int a) { age = a; } public int getAge() { return age; } }, age is the data, Dog(int a) sets it up, and getAge() reports it.

Constructors initialize state

The constructor runs once, when you call new, and its job is to give the new object its starting state. new Dog(4) runs Dog(int a) with a = 4, storing 4 in the instance variable age. If a class does not declare a constructor, Java supplies a default one that leaves fields at their default values.

Accessor vs. mutator methods

Methods fall into two roles. An accessor (getter) reports state without changing it, like getAge() returning age. A mutator (setter) changes state, like an increment() method that does count++. Reading whether a method returns a value or modifies a field tells you which role it plays and what the object looks like afterward.

A minimal class
class C { private T field; C(T v){ field = v; } T getField(){ return field; } }
Instance variable + constructor + accessor is the core shape of nearly every AP class.
Worked example

Given class Counter { private int count = 0; public void increment() { count++; } public int getCount() { return count; } }, trace: Counter c = new Counter(); then c.increment(); then c.increment(); then System.out.println(c.getCount());

  1. 1.new Counter() builds an object whose count starts at 0.
  2. 2.First c.increment() runs count++, making count 1.
  3. 3.Second c.increment() runs count++ again, making count 2.
  4. 4.c.getCount() returns the current count, 2.
Answer: It prints 2 — two increments raise the count from 0 to 2.
Checkpoint

Given `class Dog { private int age; public Dog(int a) { age = a; } public int getAge() { return age; } }`, what does this print? `Dog d = new Dog(4);` then `System.out.println(d.getAge());`

Tip

A constructor has the same name as the class and no return type — not even void. If you accidentally give it a return type, Java treats it as an ordinary method, not a constructor.

Checkpoint

Given `class Counter { private int count = 0; public void increment() { count++; } public int getCount() { return count; } }`, what does this print? `Counter c = new Counter();` then `c.increment();` then `c.increment();` then `System.out.println(c.getCount());`

On the exam

Track an object’s state across a sequence of calls by keeping a running note of each instance variable. Mutator calls change it; accessor calls only read it.

Answer the 2 checkpoints as you read.

Sign in to save your progress