ProgrammingVery hardProduct company OA

What is printed?

What is printed?
class Base {
    void greet(Object o) { System.out.print("Object "); }
}
class Derived extends Base {
    void greet(String s) { System.out.print("String "); } // overload, not override
}
// in main:
Derived d = new Derived();
Base b = d;
b.greet("hi");
d.greet("hi");
  1. A. String String
  2. B. Object String
  3. C. Object Object
  4. D. String Object

Correct answer: B. Object String

greet(String) in Derived is a NEW OVERLOAD (different parameter type), not an override of greet(Object); overload resolution happens at compile time based on the STATIC type of the reference. b's static type is Base, which only has greet(Object), so b.greet("hi") calls that, printing "Object". d's static type is Derived, which offers both overloads and picks the more specific greet(String), printing "String".

More OOP with C++ and Java questions

Exams that ask this topic