ProgrammingHardProduct-company MCQ pattern

What is printed?

What is printed?
class Base {
    public Base() { System.out.print("Base "); }
    public Base(Base other) { System.out.print("BaseCopy "); }
}
class Sub extends Base {
    public Sub() { System.out.print("Sub "); }
    public Sub(Sub other) { super(other); System.out.print("SubCopy "); }
}
public class Main {
    public static void main(String[] args) {
        Sub s1 = new Sub();
        Sub s2 = new Sub(s1);
    }
}
  1. A. Base Sub BaseCopy SubCopy
  2. B. Base Sub Base SubCopy
  3. C. Base Sub Sub SubCopy
  4. D. Compile-time error: Base has no constructor matching Base(Sub)

Correct answer: A. Base Sub BaseCopy SubCopy

Java has no built-in copy constructors; Sub(Sub other) is just an ordinary overloaded constructor someone wrote. new Sub() runs Base() then Sub() (printing Base Sub). new Sub(s1) calls super(other) explicitly, matching Base(Base other) since Sub is-a Base, printing BaseCopy, then Sub(Sub other)'s own body prints SubCopy.

More OOP with C++ and Java questions

Exams that ask this topic