Java BankAccount Class Object Reference Textbook Question (simple question but I just can't seem to figure it out)

48 Views Asked by At

the following code is given in a class and a main method. answer is below the code. just cant seem to figure out why the code returns what it does.

public class BankAccount {
    private double balance;

    public BankAccount(double init) {
        balance = init;
    }
    public void deposit(double amt) {
        double newBalance = balance+amt;
        balance = newBalance;
    }
    public double getBalance() {
        return balance;
    }
}
public class Main {

    public static void main(String[] args) {
        BankAccount b1 = new BankAccount(500);
        BankAccount b2 = b1;
        b1.deposit(b2.getBalance());    
        b2.deposit(b1.getBalance());
        System.out.println(b1.getBalance());
        System.out.println(b2.getBalance());
    }
}

the values of accounts after running are: b1=2000 and b2=2000. Why?

1

There are 1 best solutions below

0
Nick Kress On

b2 is a reference to b1. Essentially you are depositing all to the same account, then getting the same balance as the output.

  BankAccount b1 = new BankAccount(500);
  BankAccount b2 = b1; --> reference to b1
  
  b1.deposit(b2.getBalance()); --> deposit 500, new balance = 1000
  b2.deposit(b1.getBalance()); --> deposit 1000, new balance = 2000