Java Programming - Inner Classes - Discussion

Discussion :: Inner Classes - Finding the output (Q.No.3)

3. 

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: Option D

Explanation:

This code would be legal if line 11 ended with a semicolon. Remember that line 5 is a statement that doesn't end until line 11, and a statement needs a closing semicolon!


Madhu said: (Jun 26, 2010)  
Plz explain how the semicolon plays a significant role here. Am not getting the syntax of adding semicolon at line 11.

Please explain above programme in detail.

Thanx in advance.

Dips said: (Nov 7, 2010)  
How come the code from line 5 to line 11 becomes a statement? I'm getting confused, please respond as quickly as possible.

Thomas said: (Feb 4, 2011)  
No need to be confused. In line 5 a method inner class, that inherits from Object is defined. This ends with the line after the line marked as Line 11. Read more on:

http://download.oracle.com/javase/tutorial/java/javaOO/innerclasses.html

Zorba said: (Mar 24, 2012)  
It's an anonymous class - google it.

They are used to overwrite methods in the initial class.
Here the method equals in the class Object is overwritten.
Did it helped ?

A semicolon is mandatory after such a declaration.

Sohi said: (Sep 11, 2013)  
Normally we use like :

Object o = new Object();

Hence we are creating anonymous class the syntax will looks like:

Object o = new Object(){ /*-code for anonymous class--*/};

From Question if it should be like:

Object o = new Object(){
public boolean equals(Object obj)
{
return true;
}
}; /* Line 11 */

Bhanu Pratap Singh said: (Aug 4, 2014)  
System.out.println(o.equals("Fred")); This line is calling the equals() function with "Fred" as a argument.

But this function is accepting Object value.

I am not understanding this code ?
Why we are not using following line.

/**********************************************/
public boolean equals(String s){
return true;
}
/**********************************************/

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.