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());- A. AA
- B. BA
- C. BAA
- 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
- What happens when Z is compiled? java interface X { int V = 1; } interface Y { int V = 2; } class Z implements X, Y { int get() { return…
- What happens when this is compiled? java interface A { default void hello() { System.out.print("A"); } } interface B extends A { void…
- How many of these statements about Java exceptions are correct? (i) An overriding method may throw any unchecked exception, even if the…
- What happens when this code is compiled? java try { new java.io.FileReader("x.txt"); } catch (java.io.IOException | Exception e) {…
- What is printed? java try { throw null; } catch (NullPointerException e) { System.out.print("NPE"); } catch (Exception e) {…
- What is printed? java int i = 0; while (true) { try { i++; if (i == 3) break; } finally { System.out.print(i); } }