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);
  1. A. C:A
  2. B. C:B
  3. C. A
  4. 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

Exams that ask this topic