2

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.

ArtisticMelody
  • 63
  • 1
  • 2
  • 8
  • 1
    Please conform to Java coding conventions: Type names (class,interface,enum) should start with a capital letter (e.g. `BigPicture`). Method, variable and field names should start with a lowercase letter (e.g. `bigPicture`), and constants should be all-caps (e.g. `BIG_PICTURE`). – RealSkeptic Sep 14 '15 at 20:53
  • 3
    Putting aside how confusing it is the number of times you use "balance", please show us *how* you're using this class. Your description is too vague. – Zong Sep 14 '15 at 20:54
  • and setters must start with set e.g. setBalance – Manos Nikolaidis Sep 14 '15 at 20:54
  • Everytimes you use `new something()` it creates a new instance (i.e. in your case a balnce instance with balance equal to 0), that's probably your issue –  Sep 14 '15 at 20:57
  • 1
    It seems to me the balance should be part of an `Account` class, not its own class. – GriffeyDog Sep 14 '15 at 21:04
  • You need to show us how you use the balance class. When and how do you call `getBalance` and `returnBalance`? Without this information we can only guess what is wrong. – Stefan Dollase Sep 14 '15 at 21:07
  • No answers in the question, please. I have rolled back/edited your question and removed the answer. Add the answer in the answer section only. – Sabito stands with Ukraine Feb 22 '21 at 21:29

6 Answers6

0

If you want all your objects to share the same balance field you have to add the static modifier. Otherwise a new member will be created for every objects.

ouah
  • 142,963
  • 15
  • 272
  • 331
0

If you need just a copy with same balance,

public class Balance {
private int balance;

    public int getBalance()
    {
        return balance;
    }

    public void setBalance(int b)        
    { 
         balance=b;
    }

    public Balance newBalance()
    {
         Balance b=new Balance();
         b.setBalance(getBalance());
         return b;
    }
  }

usage:

  balanceCall=previousBalance.newBalance();

or you can clone too.

huseyin tugrul buyukisik
  • 11,469
  • 4
  • 45
  • 97
0

Assuming the methods are called correctly, you can share your balance variable by using the static keyword (ex. "static int balance;").

In doing so, you make the variable belongs to all classes within the project and is shared across them. To use this variable, just refer to its name, in this case use "balance = [insert formula];" (no longer need to use "this.balance").

cleed
  • 11
  • 3
0

You are creating a new instance of the balance class when you do new balance(). So essentially one class is still referring to the old instance, while the new class is referring to the new one.

The way you should go about this depends a bit on the rest of the program, but if you want to refer to the same instance, you should put an extra method in the balance class, called updateBalance() which changes the balance, or maybe decrements / increments it depending on whether it is a withdrawal or deposit.

However, your design seems to be a bit weird. It seems that both classes performing withdrawals or deposits should actually be referring to the same bank account. The balance class seems a bit redundant.

jbx
  • 21,365
  • 18
  • 90
  • 144
  • Is there a better way to share a variable between classes? – ArtisticMelody Sep 14 '15 at 21:15
  • It depends what you want to do. If its simply passing one object to another, you just pass the reference to it (not create a new one) to the other class. You can do it as a method parameter for instance. For example, lets say you have a `BankTransfer` class, which has a method `transferFunds(BankAccount from, BankAccount to)` ... it has a reference to both bank accounts and can thus update the balance of both – jbx Sep 14 '15 at 21:22
  • 2
    For the record, I don't quite agree with the `static` approach. This means all the balance instances throughout the program will have the same value. So it means there can't be 2 different bank accounts with 2 different balances. – jbx Sep 14 '15 at 21:26
0

The static behaviour approach as suggested by others definitely helps achieve a solution, but, keeping in mind your opening line that you're still a beginner in Java, I'd suggest you change your Class design altogether, to make it more in line with an Object Oriented design.

Create a class called Account, with Balance as its attribute. It makes sense to have an Account object (like in the real-world) that HAS a Balance attribute. The withdraw or deposit actions corresponding to an Account can be put within the same Account class, in line with the encapsulation paradigm of OOP/Java. This would help in making it more intuitive to understand the flow of variables within your program.

public class Account{
   public int balance = 0;

   public void setBalance(int balance){
      this.balance = balance;
   }

   public int getBalance(){
      return this.balance;
   }

   public deposit(int amount){
      this.balance += amount;
   }

   public withdraw(int amount){ 
      //Additional validations can be added to ensure non-negative balance, if needed
      this.balance -= amount;
   }
}

public AccountDemo{
   public static void main(String[] args){
     Account account1 = new Account();
     account1.deposit(100);
     Account account2 = new Account();
     account2.deposit(50);
     account2.withdraw(10);
     //account1 has a balance of 100 & account2 has a balance of 40 at this point

     AccountDemo.transferMoney(account1, account2, 20);
     //account2 now has a balance of 80 (deducted by 20) 
     // & account2 has a balance of 60(increased by 20) after the transfer.

  }

  public static boolean transferMoney(Account source, Account destination, int amount){
    if(source.getBalance() >= amount){
       source.withdraw(amount);
       destination.deposit(amount);
       System.out.println("Transfer successful");
       return true;
    } else{
       System.out.println("Sorry. Transfer failed due to 
          insufficient funds.");
       return false;
    }

  }
}
Sarath Chandra
  • 1,850
  • 19
  • 40
0

This seems to be a problem with thread synchronization, namely lost update. This means, if you read and write the same value from multiple threads, some calculations will not be represented in the final result. You can solve this problem using the class AtomicInteger:

public class Balance {
    private AtomicInteger value = new AtomicInteger();

    public int get() {
        return value.get();
    }

    public void set(int value) {
        this.value.set(value);
    }

    public int addAndGet(int value) {
        return this.value.addAndGet(value);
    }
}

Right usage:

    int value = balance.addAndGet(25);

Wrong usage:

    int value = balance.get();
    value = value + 25;
    balance.set(25);

You have to use the addAndGet method to prevent the problem of lost update.

Also, you should definitely not declare the value attribute as static, because then all of your Balance instances will hold the same value which is probably not what you want.

See also:

Community
  • 1
  • 1
Stefan Dollase
  • 4,530
  • 3
  • 27
  • 51