Machine-translated by Google. Questions are authored in English.
Top

Discussion

What will be the output of the program?

public class TestObj 
{
    public static void main (String [] args) 
    {
        Object o = new Object() /* Line 5 */
        {
            public boolean equals(Object obj) 
            {
                return true;
            } 
        }      /* Line 11 */
        
        System.out.println(o.equals("Fred"));
    }
}

  • A.It prints "true".
  • B.It prints "Fred".
  • C.An exception occurs at runtime.
  • D.Compilation fails

Answer: D

Correct answer: Compilation fails

The anonymous class is an expression, so the statement assigning it must end in a semicolon. The closing brace on line 11 is not followed by one, and the compiler reports the error there. Had the semicolon been present the program would have printed true, since the overridden equals returns true for any argument - which is what the first option describes.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.