Given: 1. interface TestA { String toString(); } 2. public class Test { 3. public static void main(String[] args) { 4. System.out.println(new TestA() { 5. public String toString() { return “test”; } 6. }); 7. } 8. } What is the result?

  1. test

  2. null

  3. Compilation fails because of an error in line 1

  4. Compilation fails because of an error in line 5


Correct Option: A
Explanation:

To solve this question, the user needs to understand the concept of anonymous inner classes and the toString() method.

Explanation of the code:

  • An interface TestA is defined in line 1 with a single method toString().
  • In line 4, an anonymous inner class is created that implements the TestA interface and overrides the toString() method to return the string "test".
  • In line 6, the toString() method of the anonymous inner class is called, which returns "test".
  • In line 4, the anonymous inner class is passed as an argument to the println() method of System.out, which prints the value returned by the toString() method to the console.

Options Explanation:

  • Option A: This option is correct because the output of the program is "test", which is returned by the toString() method of the anonymous inner class.
  • Option B: This option is incorrect because the output of the program is not null.
  • Option C: This option is incorrect because there is no error in line 1. The interface TestA is defined correctly.
  • Option D: This option is incorrect because there is no error in line 5. The toString() method is overridden correctly.

The answer is: A. test

Find more quizzes: