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
2The 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:0Reassigning 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