I'm pretty new to Java and need some help with a program I am writing. Basically I have 2 classes that are trying to change the balance of a bank account. One class is adding deposits while the other is withdrawing. I though the easiest way to share a balance between the classes was to make a third class that looks like this:
public class Balance {
static int balance;
public int getBalance(){
return balance;
}
public void returnBalance(int bal){
this.balance = bal;
}
}
I am correctly calling the getBalance method because that is pulling in the correct balance. However, when I use my object Balance balanceCall = new Balance();
to give the changed balance (after depositing), it is not updating the balance within the class. I think I am again calling the method correctly, but it does not appear to actually change the value of the balance variable in my balance class. Is the code in my balance class used incorrectly for the returnBalance
method?
Thanks for your help!
UPDATE: I changed the integer to static int balance. It is now updating the value between classes, however it seems to be creating a new value every time i do a deposit.
This is what it looks like:
Thread 1 deposits $76 Balance is $76
Thread 8 withdraws $45 Balance is $31
Thread 7 withdraws $12 Balance is $64
Thread 6 withdraws $41 Balance is $35
Thread 3 deposits $89 Balance is $165
Thread 5 withdraws $10 Balance is $66
Thread 4 withdraws $17 Balance is $59
Thread 2 deposits $157 Balance is $157
Here is how I use the Balance
instance:
balanceNum = balanceCall.getBalance();
balanceNum = balanceNum + 25;
balanceCall.returnBalance(balanceNum);
Hopefully this helps to clear things up.
SOLVED: After changing my variable to static int balance
, which is suitable for my program's purposes as there is only one balance needed, it almost fixed the problem. I changed around the logic a tad and now it works. Instead of updating the balance and sending this value back to the Balance class I created a new method in the Balance class and sent it the value of how much I wanted to withdraw/deposit and then the string "Withdraw" or "Deposit" to perform the correct calculation. Now it seems to update the balance correctly. Thanks all for your help!