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());
}
}- A. Base
- B. Sub
- C. Compile-time error: cannot widen access from protected to public in an override
- 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
- What is printed? java class Shape { double area() { return 0.0; } } class Rectangle extends Shape { double w, h; Rectangle(double w…
- What is printed? java class Vehicle implements Comparable<Vehicle> { int speed; Vehicle(int s) { speed = s; } public int compareTo(Vehicle…
- What is printed? cpp struct Base { virtual Base& self() { cout << "Base::self "; return this; } }; struct Derived : Base { Derived& self()…
- What is printed? java enum Status { ACTIVE, INACTIVE, BANNED; boolean isUsable() { return this == ACTIVE; } } public class Main { public…
- What happens when this is compiled? java enum Operation { ADD { public int apply(int a, int b) { return a + b; } }, MULTIPLY { public int…
- What is printed? cpp struct Logger { Logger(const Logger&) = delete; Logger& operator=(const Logger&) = delete; Logger() { cout << "Ctor…