Java Programming - Inner Classes - Discussion

Discussion Forum : 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"));
    }
}
It prints "true".
It prints "Fred".
An exception occurs at runtime.
Compilation fails
Answer: Option
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!

Discussion:
6 comments Page 1 of 1.

Madhu said:   2 decades ago
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:   1 decade ago
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:   1 decade ago
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:   1 decade ago
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:   1 decade ago
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:   1 decade ago
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:

Your comments will be displayed after verification.