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);- A. I-am-Derived
- B. a default Object-style toString of Base
- C. Compilation error: clone2 return types conflict
- 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
- 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…
- What is printed? java class Shape { double scale = 1.0; double area() { return 0; } } class Circle extends Shape { double r; Circle(double…
- What is printed? java class Base { protected int code() { return 1; } } class Mid extends Base { @Override protected int code() { return…
- What is printed? cpp struct Logger { static int instances; Logger() { instances++; } ~Logger() { instances--; } }; int Logger::instances =…