AP Computer Science A · Unit 3 lecture · Part 3 of 10 · 9 min

3.3 Anatomy of a classInside a class: private data, public methods

Mr. Thompkins
Time to open the box. I'll show you one whole class, then we'll go through it part by part. Every class you write on the exam has the same skeleton.

A class starts with its header, public class StepCounter, and everything else lives between its braces. Inside, by convention, come the instance variables first, then the constructors, then the methods. Java doesn't care about that order, but readers do, and so does anyone grading your FRQ.

1public class StepCounter12{3    private String owner;24    private int steps;25    private int goal;267    public StepCounter(String owner, int goal)38    {9        this.owner = owner;10        this.goal = goal;11        steps = 0;12    }1314    public void walk(int n)415    {16        steps += n;17    }1819    public int stepsLeft()520    {21        if (reachedGoal())22        {23            return 0;24        }25        return goal - steps;26    }2728    private boolean reachedGoal()629    {30        return steps >= goal;31    }32}
  1. line 1 Class header: public class, then the name
  2. line 3-5 Instance variables: private, one set per object
  3. line 7 Constructor: same name as the class, no return type
  4. line 14 void method: changes the object, gives nothing back
  5. line 19 Non-void method: returns an int
  6. line 28 private helper: only code inside the class can call it
A complete class. Each numbered mark is one part of the anatomy.
?Wait, what do public and private actually control?
They control which code may use a name. public means any class can use it. private means only code written inside this same class can use it. They are called access modifiers. They don't change what the code does, only who may call or read it.

Here's the rule for this course. The class itself is public. Instance variables are always private. Constructors are public. Methods are public when clients need them and private when they are only helpers for the class's own code, like reachedGoal. This is encapsulation: the data is sealed inside the object, and the only way in is through methods the author chose to offer.

Why seal it? Because then the author controls every change. If steps were public, any client could write mine.steps = -500 and the object would be nonsense. With steps private, the only ways to change it are the ones the class allows, so the class can keep its data valid.

1StepCounter mine = new StepCounter("Kai", 8000);2mine.walk(3500);13mine.walk(2700);14System.out.println(mine.stepsLeft());25mine.walk(2000);6System.out.println(mine.stepsLeft());3
  1. line 2-3 3500 + 2700 = 6200 steps so far
  2. line 4 8000 - 6200 = 1800 left
  3. line 6 8200 >= 8000, so the helper says the goal is reached
output › 1800 0
A client uses the object only through its public methods.
1// in a client class, not inside StepCounter2StepCounter mine = new StepCounter("Kai", 8000);3mine.steps = 99999;14mine.reachedGoal();2
  1. line 3 error: steps has private access in StepCounter
  2. line 4 error: reachedGoal() has private access in StepCounter
output › compile error (2 errors): both lines reach for private parts
What happens when a client reaches for private parts. These are the real compiler messages.
Pause and think
Why does it make sense for reachedGoal to be private, even though it's a perfectly good method?
I thought about it. Show me
Clients don't need it: stepsLeft already gives them the answer they care about. Keeping it private means the author can rename it, change it or delete it later without breaking anyone's code. Make a method public only when a client truly needs it.
?Wait, what does steps += n do?
It's compound assignment: steps = steps + n. It adds n to the current value and stores the result back in steps. You also have -=, *=, /= and %=, plus steps++ for adding exactly 1.

Notice that methods inside the class use steps and goal freely, with no dot and no getter. Instance variables belong to the object, and an instance method always runs on some object, the one before the dot in the call. When the client writes mine.walk(3500), the steps inside walk means mine's steps.

Trace the object

What does this client code print? Use the StepCounter class above.

StepCounter s = new StepCounter("Rui", 5000);
s.walk(1200);
s.walk(4100);
System.out.println(s.stepsLeft());
s.walk(-400);
System.out.println(s.stepsLeft());
  1. The constructor sets owner to "Rui", goal to 5000 and steps to 0.
  2. walk(1200) makes steps 1200. walk(4100) makes it 5300.
  3. stepsLeft calls the helper: 5300 >= 5000 is true, so it returns 0. The first line printed is 0.
    Why?
    The helper runs on the same object, so it sees the same steps.
  4. walk(-400) is legal: nothing stops a negative argument. steps becomes 4900.
    Why?
    This is a design gap. A comment could state the precondition n > 0, or the method could check it. You'll see preconditions in 3.5.
  5. stepsLeft again: 4900 >= 5000 is false, so it returns 5000 - 4900 = 100.

Answer: It prints 0, then 100.

Stuck? Get a hint
  1. Write steps in a box and update it after every call.
  2. After the first two walks, steps is 5300. Is that at least the goal?
  3. walk(-400) subtracts. Then compare 4900 with 5000.
Check yourself
Which statement compiles in a client class?
StepCounter s = new StepCounter("Lu", 5000);
  1. As.walk(200);
  2. Bs.steps += 200;
  3. Cs.reachedGoal();
  4. DStepCounter.walk(200);
Show the answer

A. walk is public, so a client can call it on an object. steps and reachedGoal are private, so the second and third choices don't compile. The last choice calls walk on the class name, which only works for static methods, and walk is not static.

Exam tip from Mr. T

On the Class Design FRQ, one point is just for declaring the instance variables private. It's the easiest point on the exam. Never skip it, and never make an instance variable public to save time.

  • Skeleton: public class header, private instance variables, public constructors, then methods.
  • Encapsulation: data is private and reachable only through the methods the author offers.
  • Clients use public methods; private helper methods serve the class's own code.
  • Inside an instance method, an instance variable means the variable of the object the method was called on.