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);- A. derived-result
- B. base-result
- C. Compilation error: return type String is incompatible with Object
- 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
- What is printed? cpp class Logger { public: static Logger& instance() { static Logger inst; return inst; } void log(const string& msg) {…
- What is printed? java class EventBus { private static EventBus instance; private EventBus() { System.out.print("created "); } public…
- What is printed? java class Base { Base clone2() { return new Base(); } } class Derived extends Base { @Override Derived clone2() { return…
- What is printed? java class Animal { void makeSound() { System.out.print("..."); } } class Dog extends Animal { @Override void makeSound()…
- What is printed? java class Base { Base() { System.out.print("Base "); } } class Mid extends Base { Mid() { System.out.print("Mid "); } }…
- What is printed? cpp struct Base { virtual void render() const { cout << "Base::render "; } }; struct Derived : Base { void render() const…