Writing Classes
- Identify the parts of a class: instance variables, a constructor, and methods
- Trace object creation followed by method calls on that object
- Distinguish methods that change state from methods that report it
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.
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.
new Counter()builds an object whosecountstarts at 0. - 2.First
c.increment()runscount++, making count 1. - 3.Second
c.increment()runscount++again, making count 2. - 4.
c.getCount()returns the current count, 2.
2 — two increments raise the count from 0 to 2.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());`
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.
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());`
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