ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
class Account {
    protected double balance;
    Account(double b) { balance = b; }
    void transfer(Account to, double amt) {
        this.balance -= amt;
        to.balance += amt;
    }
}
class SavingsAccount extends Account {
    SavingsAccount(double b) { super(b); }
}
public class Main {
    public static void main(String[] args) {
        SavingsAccount a = new SavingsAccount(100);
        SavingsAccount b = new SavingsAccount(50);
        a.transfer(b, 30);
        System.out.println(a.balance + " " + b.balance);
    }
}
  1. A. 100.0 50.0
  2. B. 70.0 80.0
  3. C. 130.0 20.0
  4. D. Compile-time error: to.balance is not accessible since to is a different object

Correct answer: B. 70.0 80.0

A protected member is freely accessible between two objects of the same class (or same package, or subclass relationship) from within a method of that class — accessibility is about the code's location, not a specific object instance here, and both ends are SavingsAccount in the same package. transfer() deducts 30 from a's balance (100-30=70) and adds it to b's (50+30=80).

More OOP with C++ and Java questions

Exams that ask this topic