ProgrammingHardTCS NQT · Infosys pattern

What is printed?

What is printed?
class Base {
    protected Object clone2() { return new Base(); }
}
class Sub extends Base {
    @Override
    public Object clone2() { return new Sub(); }
}
public class Main {
    public static void main(String[] args) {
        Base b = new Sub();
        Object o = b.clone2();
        System.out.println(o.getClass().getSimpleName());
    }
}
  1. A. Base
  2. B. Sub
  3. C. Compile-time error: cannot widen access from protected to public in an override
  4. D. Compile-time error: clone2 conflicts with Object.clone

Correct answer: B. Sub

Widening access (protected -> public) when overriding is always allowed in Java, only narrowing is forbidden. Sub.clone2() legally overrides Base.clone2() with wider visibility. b.clone2() dispatches dynamically to Sub's version, which constructs and returns a new Sub, so getSimpleName() reports Sub.

More OOP with C++ and Java questions

Exams that ask this topic