ProgrammingHardWipro · Cognizant pattern
What is printed?
What is printed?
class Base {
Base self() { return this; }
}
class Derived extends Base {
@Override
Derived self() { return this; }
String tag() { return "D"; }
}
// in main:
Base b = new Derived();
System.out.println(((Derived) b.self()).tag());- A. D
- B. Compilation error: self() return type mismatch
- C. ClassCastException at run time
- D. null
Correct answer: A. D
Derived's self() covariantly overrides Base's to return Derived, and b.self() dispatches virtually to it, returning the actual Derived object (no slicing, since these are references/pointers conceptually—here object references). The cast to Derived is safe at run time (it really IS a Derived), so tag() prints "D".
More OOP with C++ and Java questions
- What is printed? java class Account { private double balance; Account(double b) { balance = b; } void withdraw(double amt) { if (amt >…
- What is printed? java class Task { void execute() throws Exception { try { riskyStep(); } catch (RuntimeException e) { throw new…
- What is printed? cpp class Base { public: virtual void op() { cout << "Base::op "; } void callOp() { this->op(); } }; class Derived…
- What is printed? cpp struct Base { virtual std::string name() const { return "Base"; } }; struct Derived : Base { std::string name() const…
- What is printed? java class Resource { String name; Resource(String n) { name = n; } @Override protected void finalize() {…
- What is printed? cpp class Logger { public: static int instances; Logger() { instances++; } ~Logger() { instances--; } }; int…