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

Respuesta :

kanat

This question is incomplete, it lacks a piece of code to analyze.

I think you wanted an answer to the following question:

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;

   @Override

   public String toString() {

       return "A's x is " + x;

   }

}

A. When executing System.out.println(a1), the toString() method in the Object class is invoked.

B. When executing System.out.println(a2), the toString() method in the Object class is invoked

C. When executing System.out.println(a1), the toString() method in the A class is invoked.

D. The program cannot be compiled, because System.out.println(a1) is wrong and it should be replaced by System.out.println(a1.toString())

E. Both B and C.

Answer:

E. Both B and C.

Explanation:

toString() method is used to get the representation of this object as a string. When trying to display a string representation of an object usually the full name of the class will be displayed.

In the example above, line

System.out.println(a2);

would display something like

java.lang.Object@5ccd43c2

Obtained value can hardly serve as a good string description of an object. Therefore, toString() method is often overridden using @Override annotation (more info about @Override at https://beginnersbook.com/2014/07/override-annotation-in-java/)

Line  

System.out.println(a1);

would display "A's x is 0" because it uses toString() method overridden in class A.