ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
class Base {
    public Object process() { return "base-result"; }
}
class Derived extends Base {
    @Override
    public String process() { return "derived-result"; }
}
// in main:
Base b = new Derived();
Object result = b.process();
System.out.println(result);
  1. A. derived-result
  2. B. base-result
  3. C. Compilation error: return type String is incompatible with Object
  4. D. ClassCastException at run time

Correct answer: A. derived-result

String is a subtype of Object, so Derived.process() returning String is a legal covariant-return override of Base.process() returning Object. Dynamic dispatch picks Derived's version, and assigning the String result to an Object variable is a trivial widening reference conversion, so "derived-result" prints.

More OOP with C++ and Java questions

Exams that ask this topic