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);
}
}- A. Base Sub BaseCopy SubCopy
- B. Base Sub Base SubCopy
- C. Base Sub Sub SubCopy
- 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
- What is printed? cpp struct Base { virtual void run() { step1(); step2(); } virtual void step1() { cout << "B1 "; } virtual void step2() {…
- What is printed? java class Account { protected double balance; Account(double b) { balance = b; } void transfer(Account to, double amt) {…
- What is printed? cpp struct Base { Base() { cout << "Base "; } Base(int x) { cout << "Base(" << x << ") "; } }; struct Derived : Base {…
- What is printed? java class Node<T> { T value; Node<T> next; Node(T v) { value = v; } } public class Main { static <T> int length(Node<T>…
- What is printed? cpp struct Shape { virtual ~Shape() = default; }; struct Circle : Shape {}; struct Square : Shape {}; int main() { Shape…
- What is printed? java class Base { void process() { System.out.print("Base.process "); validate(); } protected void validate() {…