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?
b2 is a reference to b1. Essentially you are depositing all to the same account, then getting the same balance as the output.