Beginning object oriented programming in Java: public class BankAccount{ private double myBalance; public BankAccount(double initialBalance){ myBalance = initialBalance; } public void deposit(double amount){ double newBalance = myBalance + amount; myBalance = newBalance; } public double getBalance(){ return myBalance; } }
//in another class public class driver { public static void main(String [] args){ BankAccount b1 = new BankAccount(500); BankAccount b2 = new BankAccount(200); b1.deposit(b2.getBalance()); b2.deposit(b1.getBalance()); } }
What are the balances of b1 and b2 after the code is executed?
The code that confuses me is b1.deposit(b2.getBalance()); First, the value of b2 goes into the method getBalance, which returns 200. Now it is b1.deposit(200); but what does that do? I don't understand and the debugger isn't much help.
Please explain. How does that happen?
Like, in the first time you run b1.deposit(b2.getBalance()); why does amount = 200 and mybalance = 500?? It says that in my debugger. I don't understand that one bit.
Shouldn't amount = 500 and mybalance = 200?
Inside the main(), the 1st line says B1 = 500 the 2nd line says B2 = 200. The third line says that you're depositing the amount of money in B2 into B1, therefore 500+200 = 700 dollars. The fourth line says that you're now depositing the amount of money from B1 into B2, so 200 + 700 = 900 dollars. Therefore, B1 has 700 dollars and B2 has 900 dollars.
MAH sleek-feathered oneH! Okay, I think I understand it way better now. :) Thank you again!
Join our real-time social learning platform and learn together with your friends!