ProgrammingVery hardAmazon/Microsoft SDE MCQ · Java placement

What is printed?

What is printed?
class A { void m(A a) { System.out.print("AA"); } }
class B extends A {
    void m(A a) { System.out.print("BA"); }
    void m(B b) { System.out.print("BB"); }
}
// in main:
A x = new B();
B y = new B();
x.m(y);
y.m(x);
y.m(y);
  1. A. BBBABB
  2. B. BABABB
  3. C. AABABB
  4. D. BBBBBB

Correct answer: B. BABABB

The overload is chosen at compile time from static types: x is an A, which only has m(A), so x.m(y) means m(A), overridden in B: BA. y.m(x) passes an A: BA. y.m(y) picks the more specific m(B): BB.

More OOP with C++ and Java questions

Exams that ask this topic