Analyze the following code: public class Test { public static void main(String[] args) { Object a1 = new A(); Object a2 = new Object(); System.out.println(a1); System.out.println(a2); } } class A { int x; public String toString() { return "A's x is " + x; } }

Analyze the following code:
public class Test {
  public static void main(String[] args) {
    Object a1 = new A();
    Object a2 = new Object();
    System.out.println(a1);
    System.out.println(a2);
  }
}
class A {
  int x;
  public String toString() {
    return "A's x is " + x;
  }
}


A. The program cannot be compiled, because System.out.println(a1) is wrong and it should be replaced by System.out.println(a1.toString());
B. When executing System.out.println(a1), the toString() method in the Object class is invoked.
C. When executing System.out.println(a2), the toString() method in the Object class is invoked.
D. When executing System.out.println(a1), the toString() method in the A class is invoked.

The correct answer is CD

Explanation: Since a1 is an instance of A, the toString() method in the A class is invoked at runtime.
Sections 11.7-11.8


Java

Learn More Multiple Choice Question :