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());
  1. A. D
  2. B. Compilation error: self() return type mismatch
  3. C. ClassCastException at run time
  4. 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

Exams that ask this topic