AP · Computer Science A · Anatomy of a Class

Instance Variables and Encapsulation

13 min readUpdated December 1, 2026FreeAP Computer Science A, Class Creation

An object's state is the set of values in its instance variables, and its behavior is what its methods do. Instance variables are declared private, so only the class's own code can read or change them; other classes go through public methods. Methods that report state are accessors, methods that change it are mutators, and hiding the data behind them is called encapsulation.

Quick check

  1. What does String w = "hi"; int n = w.length(); store in n?Show answerHide answer
    1. length() is a method called on the object w, and it returns a value that is stored in n.
  2. Can a method with return type void be used on the right side of an assignment, as in int x = obj.doIt();?Show answerHide answer

    No. A void method returns no value, so there is nothing to store, and the code does not compile.

  3. Two Lamp objects are created and only one is switched on. Is the other one on?Show answerHide answer

    No. Each object has its own copy of every instance variable, so changing one object leaves the other as it was.

Know these already? Jump to the practice questions

What you'll be able to do

  • State what an object's instance variables and methods represent.
  • Explain what private and public allow, and why instance variables are private.
  • Identify accessor and mutator methods from their headers.
  • Determine what an object holds after a sequence of method calls.

Key terms

Instance variable

A variable declared in a class, outside any method. Every object of the class has its own copy.

In plain English
Something each object remembers about itself.
Don't write
"All objects of a class share one copy of each instance variable."

Encapsulation

Keeping an object's instance variables private so that other classes can reach the data only through the class's methods.

In plain English
The data is locked inside, and the methods are the only doors.
Don't write
"Encapsulation means the data can never change."

Accessor method

A method that returns information about an object's state without changing it.

In plain English
A "tell me" method, such as getBrightness().
Don't write
"An accessor sets an instance variable."

Mutator method

A method that changes the value of one or more instance variables.

In plain English
A "change this" method, such as setBrightness(50).
Don't write
"A mutator must return the new value."

What are an object's state and behavior?

A class lists the instance variables every object will have and the methods every object can run.

public class Lamp
{
    private boolean on;
    private int brightness;

    public void switchOn()
    {
        on = true;
    }

    public int getBrightness()
    {
        return brightness;
    }
}

A Lamp object's state is its current on and brightness values; its behavior is switchOn and getBrightness. After Lamp desk = new Lamp(); Lamp hall = new Lamp(); desk.switchOn(); only desk has on equal to true, because each object has its own copy.

An instance variable that is never assigned starts with a default value: 0 for int, 0.0 for double, false for boolean and null for an object reference such as a String. So a new Lamp starts off, at brightness 0. The note on writing constructors shows how to choose starting values.

Check yourself

After the three statements in this section, what value does hall's brightness have?
Show answerHide answer

0, the default for an int instance variable, because nothing has assigned it.

What do private and public mean?

A private member can be used only inside the body of its own class. A public member can be used from any class. Code in another class that uses an object is called client code.

Lamp desk = new Lamp();
int b = desk.getBrightness();   // compiles: public method
desk.brightness = 80;           // does not compile: private

Inside Lamp, switchOn can change on freely, because it is the class's own code. private controls where a variable can be used, not whether it can change.

Check yourself

Can client code write desk.on = true; if on is private?
Show answerHide answer

No. It does not compile; the client must call desk.switchOn() instead.

Why are instance variables private?

Encapsulation makes every change go through the class's own methods, so the class can enforce its rules. This mutator only accepts levels from 0 to 100:

public void setBrightness(int level)
{
    if (level >= 0 && level <= 100)
    {
        brightness = level;
    }
}

If brightness were public, client code could write desk.brightness = -40; and nothing in Lamp could stop it. Hiding the data also lets the class change how it stores its state later without breaking client code, because clients only ever call the methods.

Key idea

Instance variables are private so that only the class's methods can change them, and those methods can check every change.

Check yourself

brightness is 60. A client calls setBrightness(140). What is brightness now?
Show answerHide answer

Still 60. 140 fails level <= 100, so the assignment is skipped.

What are accessor and mutator methods?

Read the header and the body. An accessor has a return type other than void and returns part of the state without changing it. A mutator changes an instance variable and usually has return type void.

HeaderKindWhy
public int getBrightness()AccessorReturns brightness, changes nothing
public boolean isOn()AccessorReturns on, changes nothing
public void switchOn()MutatorSets on to true
public void setBrightness(int level)MutatorMay change brightness

Names such as getX, isX and setX are conventions, not rules: always check what the body does.

Check yourself

public void dim() lowers brightness by 10. Accessor or mutator?
Show answerHide answer

Mutator: it changes an instance variable and returns nothing.

Worked example 1: Trace two objects

Question: Using the StepCounter class, what is printed when the client code runs?

public class StepCounter
{
    private String owner;
    private int steps;

    public StepCounter(String name)
    {
        owner = name;
        steps = 0;
    }

    public int getSteps()
    {
        return steps;
    }

    public void walk(int n)
    {
        if (n > 0)
        {
            steps += n;
        }
    }

    public void reset()
    {
        steps = 0;
    }
}
StepCounter a = new StepCounter("Ana");
StepCounter b = new StepCounter("Ben");
a.walk(500);
b.walk(300);
a.walk(-200);
b.reset();
b.walk(150);
a.walk(250);
System.out.println(a.getSteps() + " " + b.getSteps());

What tells you the method

Several calls on two objects: keep one column per object's steps.

  1. Step 1: Trace each call.

    Calla's stepsb's steps
    both created00
    a.walk(500)5000
    b.walk(300)500300
    a.walk(-200)500300
    b.reset()5000
    b.walk(150)500150
    a.walk(250)750150
    Why

    Each call changes only the object it is called on, and walk ignores amounts that are not positive.

  2. Step 2: Evaluate the print.

    a.getSteps() returns 750 and b.getSteps() returns 150, joined with a space.

    Why

    The accessors return the final state without changing it.

Check it

a received 500 + 250 = 750 accepted steps; b was reset after its 300, leaving only 150.

Answer

750 150

Worked example 2: Design a mutator that enforces a rule

Question: A Thermostat has a private int target, set to 20 when the object is created. Design setTarget(int newTarget) so the target changes only when newTarget is from 10 to 30 inclusive. Then state what getTarget() returns after setTarget(25), setTarget(35) and setTarget(9), in that order, on a new Thermostat.

What tells you the method

A design task: state the input, the output and the rule, write the body, then test it by tracing.

  1. Step 1: State the plan.

    Input: the requested target. Output: none, so the return type is void. Rule: assign only if 10 ≤ newTarget ≤ 30.

    Why

    A method that changes state and reports nothing is a void mutator.

  2. Step 2: Write the body.

    public void setTarget(int newTarget)
    {
        if (newTarget >= 10 && newTarget <= 30)
        {
            target = newTarget;
        }
    }
    
    Why

    The && makes both limits apply; >= and <= keep 10 and 30 allowed.

  3. Step 3: Trace the calls.

    setTarget(25) passes, so target is 25. setTarget(35) fails <= 30, and setTarget(9) fails >= 10, so target stays 25.

    Why

    A rejected value leaves the state as it was.

Check it

Test the boundaries on a new object: setTarget(10) gives 10, setTarget(30) gives 30, and setTarget(31) leaves 30.

Answer

25

Worked example 3: Which client statement compiles?

Question: The class Thermostat has a private int target, a public int getTarget() and a public void setTarget(int newTarget). Client code has Thermostat t = new Thermostat();. Which statement compiles?

  • A) t.target = 22;
  • B) t.setTarget(22);
  • C) int x = t.setTarget(22);
  • D) t.getTarget(22);

What tells you the method

An access question: check each option against private, the return types and the parameter lists.

  1. Step 1: Rule out direct access.

    A uses target from client code, but target is private.

    Why

    Only Thermostat's own code can use its private members.

  2. Step 2: Check the method calls.

    B calls a public method with one int, as its header asks. C stores the result of a void method, which has no value. D passes an argument to getTarget, which takes none.

    Why

    A call must match the header's parameters, and only a non-void method can supply a value.

Check it

B is also the only option that changes the target through the method that enforces the rule.

Answer

B

Your turn

Question: What is printed when the client code runs?

public class Locker
{
    private int code;
    private boolean locked;

    public Locker(int c)
    {
        code = c;
        locked = false;
    }

    public void lock()
    {
        locked = true;
    }

    public void unlock(int attempt)
    {
        if (attempt == code)
        {
            locked = false;
        }
    }

    public boolean isLocked()
    {
        return locked;
    }
}
Locker k = new Locker(4821);
k.lock();
k.unlock(1234);
System.out.println(k.isLocked());
k.unlock(4821);
System.out.println(k.isLocked());
  1. Step 1: After creation and lock().

    code is 4821 and locked is true.

  2. Step 2: Your go: trace the two unlock calls and the two prints.

Show the full solutionHide the solution

Step 2. unlock(1234): 1234 is not 4821, so locked stays true, and the first line prints true. unlock(4821) matches, so locked becomes false, and the second line prints false.

Answer: true then false on the next line.

Traps

Trap

A private instance variable cannot be changed.

It seems right because "private" sounds like "locked". But private only limits where the variable can be used: every method inside the class can read and change it, and clients change it by calling those methods.

Can the setBrightness method change the private variable brightness?

Yes. It is inside Lamp, so it can assign brightness.

Trap

Calling a mutator on one object changes every object of that class.

It seems right because all the objects come from the same class code. But each object holds its own instance variables, so a call changes only the object it is called on.

a and b are new StepCounter objects. After a.walk(40), what does b.getSteps() return?
  1. Only a changed.

What's examined

On the AP® Computer Science A exam (Unit 3: Class Creation), multiple-choice questions ask what an object holds after a sequence of calls. In the free-response class design question you write Java code for a class, so choosing private instance variables and the right accessors and mutators matters there too.

Practice questions

The Plant class is for questions 1 to 4.

public class Plant
{
    private String name;
    private int height;
    private int waterings;

    public Plant(String n, int h)
    {
        name = n;
        height = h;
        waterings = 0;
    }

    public int getHeight()
    {
        return height;
    }

    public void water()
    {
        waterings++;
        if (waterings % 2 == 0)
        {
            height += 3;
        }
    }

    public void trim(int cm)
    {
        if (cm < height)
        {
            height -= cm;
        }
    }
}
  1. Recall Which Plant method is an accessor?
  • A) water
  • B) trim
  • C) getHeight
  • D) Plant
Show answer

Answer: C. getHeight returns height and changes nothing.

Why the others are wrong:

  • A changes waterings and sometimes height, so it is a mutator.
  • B has a parameter and changes height; taking a parameter does not make a method an accessor.
  • D is the constructor, which sets the starting state.
  1. Apply What is printed when this client code runs?
Plant p = new Plant("fern", 10);
p.water();
p.water();
p.water();
p.trim(4);
System.out.println(p.getHeight());
Show answer

Answer: 9

Marking points:

  • waterings becomes 1, 2, 3; only the second watering is even, so height goes from 10 to 13.
  • trim(4): 4 < 13, so height becomes 9.
  1. Apply What value does q.getHeight() return after this client code runs?
Plant q = new Plant("cactus", 5);
q.trim(5);
q.trim(2);
q.water();
q.water();
Show answer

Answer: 6

Marking points:

  • trim(5): 5 < 5 is false, so height stays 5.
  • trim(2) makes it 3, and the second watering adds 3, giving 6.
  1. Exam-style Which change to the Plant class would break its encapsulation?
  • A) Adding public String getName(), which returns name
  • B) Adding public void rename(String n), which sets name to n
  • C) Making getHeight a private method
  • D) Declaring height as public int height;
Show answer

Answer: D. A public instance variable lets client code change height directly, skipping the check in trim.

Why the others are wrong:

  • A gives read access through a method, so the data stays hidden.
  • B changes name through a method the class controls.
  • C hides a method from clients; that limits them but exposes no data.
  1. Exam-style addPoints should add p to points only when p is positive. A new Score starts with points at 0. Give the number of the line that stops it working.
1: public class Score
2: {
3:     private int points;
4:
5:     public void addPoints(int p)
6:     {
7:         if (p < 0)
8:         {
9:             points += p;
10:        }
11:    }
12: }
Show answer

Answer: Line 7.

Marking points:

  • The test is reversed: it adds only negative values. After addPoints(5), addPoints(-3), addPoints(4), points is -3 instead of 9.
  • Changing line 7 to if (p > 0) fixes it.
  1. Apply A Locker class has a private boolean locked. Which header suits an accessor that client code calls to find out whether the locker is locked?
  • A) public boolean isLocked()
  • B) public void isLocked()
  • C) private boolean isLocked()
  • D) public boolean isLocked(boolean locked)
Show answer

Answer: A. It is public, so clients can call it, and it returns a boolean.

Why the others are wrong:

  • B is void, so it cannot return the value.
  • C is private, so client code cannot call it.
  • D asks the caller for the very value it should report.
  1. Recall Name the principle of keeping instance variables private so that other classes reach the data only through methods.
Show answer

Answer: Encapsulation.

Marking points:

  • The class's methods control every change, so the class can enforce its rules.

Key points

Recall, then reveal

Say the main points from memory first, then check them.

Show key pointsHide key points
  • State lives in instance variables; behavior lives in methods; each object has its own copy of the state.
  • private: only the class's own code; public: any class.
  • Accessors return state without changing it; mutators change it, usually as void methods.
  • Encapsulated classes check every change inside their mutators.
  • Trace calls with one column per object.

Keep learning

Explore AP Computer Science A tutoring →

View the full Computer Science A syllabus →

More in this unit

Class Creation

All Anatomy of a Class notes

Part of Novark's AP Computer Science A notes