Unit 3 Cycle 1 Day 19: Multiple Method Interaction
Share
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.
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.