Java Programming - Objects and Collections - Discussion

Discussion Forum : Objects and Collections - Finding the output (Q.No. 9)
9.
What will be the output of the program?
public static void main(String[] args) 
{
    Object obj = new Object() 
    {
        public int hashCode() 
        {
            return 42;
        }
    }; 
    System.out.println(obj.hashCode()); 
}
42
Runtime Exception
Compile Error at line 2
Compile Error at line 5
Answer: Option
Explanation:

This code is an example of an anonymous inner class. They can be declared to extend another class or implement a single interface. Since they have no name you can not use the "new" keyword on them.

In this case the annoynous class is extending the Object class. Within the {} you place the methods you want for that class. After this class has been declared its methods can be used by that object in the usual way e.g. objectname.annoymousClassMethod()

Discussion:
3 comments Page 1 of 1.

Thiyagarajan said:   1 decade ago
Object obj = new Object() this line are not complete, that mean missing for semicolon. So answer for C. Compile error at line 2.

Ruchi said:   1 decade ago
We cannot pass the body of a function in another function and here PVSM is itself a main function.

Bic said:   1 decade ago
Don't think this code will compile without putting between "public class. {" and "}".

Post your comments here:

Your comments will be displayed after verification.