Modifying Object State Through Methods
Consider the following BankAccount and TestTransfer classes. What is printed when the main method of the TestTransfer class is executed?
public class BankAccount {
private double balance;
public BankAccount(double initialBalance) {
balance = initialBalance;
}
public void transfer(double amount, BankAccount other) {
if (amount <= balance) {
balance -= amount;
other.balance += amount;
}
}
public double getBalance() {
return balance;
}
}
public class TestTransfer {
public static void main(String[] args) {
BankAccount account1 = new BankAccount(100.0);
BankAccount account2 = new BankAccount(50.0);
account1.transfer(30.0, account2);
System.out.println(account1.getBalance() + " " + account2.getBalance());
}
}
A
The code will not compile due to accessing private fields
B
70.0 80.0
C
100.0 80.0
D
100.0 50.0
Question Leaderboard
| Rank | |||||
|---|---|---|---|---|---|
| #1 | kaisuki | 1 | 1 | 0m 00s | 100 |
| #2 | y.seong2027 | 1 | 1 | 1m 00s | 40 |
| #3 | bommasam000 | 1 | 3 | 21m 33s | -1,213 |
Items per page:
10
1 – 3 of 3
APFIVE