ProgrammingModerateProduct-company placement · Java

What is printed?

What is printed?
class A { public String toString() { return "A"; } }
class B extends A { public String toString() { return "B" + super.toString(); } }
// in main:
A x = new B();
System.out.print(x + "" + new A());
  1. A. AA
  2. B. BA
  3. C. BAA
  4. D. BAB

Correct answer: C. BAA

String concatenation calls toString(), which is dispatched on the actual object: x is a B ("B" + "A"), followed by a plain A.

More OOP with C++ and Java questions

Exams that ask this topic