ProgrammingVery hardProduct-company placement · GATE CS

What is printed?

What is printed?
class A {
    void f(Object o) { System.out.print("AO "); }
    void f(String s) { System.out.print("AS "); }
}
class B extends A {
    void f(Object o) { System.out.print("BO "); }
}
// in main:
A x = new B();
x.f("hi");
x.f((Object) "hi");
  1. A. BO BO
  2. B. AS BO
  3. C. AS AO
  4. D. BO AS

Correct answer: B. AS BO

The overload is chosen at compile time from the argument's static type: f(String) for "hi" and f(Object) for the cast. Only then does overriding pick the run-time class's version: B overrides f(Object) but not f(String), giving AS then BO.

More OOP with C++ and Java questions

Exams that ask this topic