ProgrammingVery hardWipro · Cognizant technical pattern

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);
  1. A. BB
  2. B. AA
  3. C. Compilation error: ambiguous call
  4. D. BA

Correct answer: D. BA

Overload choice happens at compile time using the static type of x (A), which has only m(A), so the signature m(A) is chosen. At run time the object is a B, which overrides m(A), so BA prints. m(B) is a separate overload that A’s type never sees.

More OOP with C++ and Java questions

Exams that ask this topic