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);
}
}- A. 100.0 50.0
- B. 70.0 80.0
- C. 130.0 20.0
- 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
- What is printed? cpp struct Base { Base() { cout << "Base "; } Base(int x) { cout << "Base(" << x << ") "; } }; struct Derived : Base {…
- What is printed? java class Node<T> { T value; Node<T> next; Node(T v) { value = v; } } public class Main { static <T> int length(Node<T>…
- What is printed? cpp struct Shape { virtual ~Shape() = default; }; struct Circle : Shape {}; struct Square : Shape {}; int main() { Shape…
- What is printed? java class Base { void process() { System.out.print("Base.process "); validate(); } protected void validate() {…
- What is printed? java class Base { public String toString() { return "Base[" + describe() + "]"; } protected String describe() { return…
- What is printed? cpp struct A { A() { cout << "A"; } }; struct B { B() { cout << "B"; } }; struct C : A, B { C() { cout << "C"; } }; int…