ProgrammingHardHCL · Tech Mahindra pattern

What is printed?

What is printed?
class Base {
    Base clone2() { return new Base(); }
}
class Derived extends Base {
    @Override
    Derived clone2() { return new Derived(); }
    public String toString() { return "I-am-Derived"; }
}
// in main:
Base b = new Derived();
Base cloned = b.clone2();
System.out.println(cloned);
  1. A. I-am-Derived
  2. B. a default Object-style toString of Base
  3. C. Compilation error: clone2 return types conflict
  4. D. null

Correct answer: A. I-am-Derived

b.clone2() dispatches virtually to Derived's override (covariant return Derived legally overrides Base), which returns a brand-new Derived instance; println on it calls its overridden toString(), printing "I-am-Derived".

More OOP with C++ and Java questions

Exams that ask this topic