Skip to main content
← AP CSA Study Guide

Code Scholars Tutoring · AP Computer Science A

7.4: Object State and Encapsulation

Keep fields private and expose methods that preserve the object's rules. Accessors observe state; mutators change it through controlled operations.

College Board Unit 3

How it works

Encapsulation means instance variables are private and outside code interacts through public methods. Accessors return state, mutators change it, and putting validation inside a mutator is what keeps an object from entering an impossible state. Two variables can refer to the same object, so a mutator called through either name changes what both observe; passing an object to a method works the same way.

Make fields private and provide only the accessors and mutators the class actually needs.

Common error

Returning a reference to a mutable field, which lets outside code change the object’s state directly.

Worked example

Java

ArrayList<String> a = new ArrayList<String>();
a.add("first");
ArrayList<String> b = a;
b.add("second");
System.out.println(a.size());

Output

2

The two references alias one object. Calling a mutator through either reference changes its state.

Exercises

7.4.1 · Trace

Determine the exact output. Explain the Java rule or state changes that produce it.

Java

ArrayList<Integer> a = new ArrayList<Integer>();
a.add(5);
ArrayList<Integer> b = a;
b = new ArrayList<Integer>();
System.out.println(a.size() + ":" + b.size());
Show solution

Output

1:0

Reassigning a copied reference does not empty the original object.

7.4.2 · Write code

Write a Wallet class with private int balance initialized to 0, getBalance(), and deposit(int amount). Ignore nonpositive deposits.

Show solution

One valid solution is shown below. Other implementations satisfying the contract are also valid.

Java

public class Wallet {
    private int balance;
    public Wallet() { balance = 0; }
    public int getBalance() { return balance; }
    public void deposit(int amount) {
        if (amount > 0) balance += amount;
    }
}

Check your code

Java

Wallet w = new Wallet(); w.deposit(8); w.deposit(-3); w.deposit(0);
System.out.println(w.getBalance());

Expected output

8
Practice this topic: MCQ →

Need help with this topic?

Work through questions with a tutor and get help with the steps you find difficult.

Get help with this topic