Unit 3 Cycle 1 Day 19: Multiple Method Interaction

Unit 3 Foundation (Cycle 1) Day 19 of 28 Foundation

Multiple Method Interaction

Section 3.6 — Writing Methods

Key Concept

When multiple methods in a class interact, understanding the order of execution and data flow is essential. Method A may call Method B, which modifies an instance variable that Method A then uses. On the AP exam, multi-method interaction problems require tracking the state of the object as methods are called in sequence. Pay attention to whether a method modifies state (mutator) or only reads state (accessor), and whether a method's return value is used by the caller or discarded.

Consider the following class.

public class Wallet { private double cash; public Wallet(double initial) { cash = initial; } public void deposit(double amount) { if (amount > 0) cash += amount; } public boolean withdraw(double amount) { if (amount > 0 && amount <= cash) { cash -= amount; return true; } return false; } public double getCash() { return cash; } }

What is printed?
Wallet w = new Wallet(100); w.deposit(50); w.withdraw(30); w.withdraw(200); System.out.println(w.getCash());

Answer: (A) 120.0

Start: 100. deposit(50): cash=150. withdraw(30): 30<=150, cash=120, returns true. withdraw(200): 200>120, returns false (no change). getCash()=120.0.

Why Not the Others?

(B) The withdraw method prevents overdrafts. 200 > 120, so the withdrawal is rejected.

(C) 150 is the cash after deposit but before any withdrawals.

(D) 100 is the initial amount, not accounting for deposit and withdrawal.

Common Mistake

The withdraw method validates the amount before modifying cash. If the withdrawal would cause overdraft, it returns false and makes no change. This is defensive programming.

AP Exam Tip

Methods that validate before modifying state are common on the AP exam. Check the condition in the if statement to determine whether the modification occurs.

Review this topic: Section 3.6 — Writing Methods • Unit 3 Study Guide

More Practice

Back to blog

Leave a comment

Please note, comments need to be approved before they are published.