ProgrammingHardProduct-company MCQ pattern
What is printed?
What is printed?
class A {
public String toString() { return "A"; }
}
class B extends A {
}
class C extends B {
public String toString() { return "C:" + super.toString(); }
}
// in main:
A x = new C();
System.out.println(x);- A. C:A
- B. C:B
- C. A
- D. Compile-time error: super.toString() is ambiguous since B does not override it
Correct answer: A. C:A
B does not override toString(), so it simply inherits A's version. C's super.toString() therefore statically resolves up the chain to the nearest actual implementation, which is A's, returning "A"; C's own override prepends "C:", giving "C:A". println dispatches dynamically to C's override since x's runtime type is C.
More OOP with C++ and Java questions
- What is printed? cpp struct A { virtual void f() { cout << "A"; } }; struct B : A { void f() override { cout << "B"; A::f(); } }; int…
- What is printed? java class Vehicle { int wheels() { return 4; } } class Motorcycle extends Vehicle { @Override int wheels() { return 2; }…
- What is printed? cpp struct Base { virtual Base clone() const { cout << "Base::clone "; return new Base(this); } }; struct Derived : Base…
- What is printed? java interface Greeter { default String hello() { return "Hi"; } } class Formal implements Greeter { @Override public…
- What is printed? cpp struct Base { Base() { cout << "Base-ctor "; } ~Base() { cout << "Base-dtor "; } }; struct Derived : Base { Derived()…
- What is printed? java public class Main { static int risky() { try { return 1; } finally { return 2; } } public static void main(String[]…