Objects and Collections

Q1: 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()); 
}

A 42

B Runtime Exception

C Compile Error at line 2

D Compile Error at line 5

ANS:A - 42

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()



img not found
img

For help Students Orientation
Mcqs Questions

One stop destination for examination, preparation, recruitment, and more. Specially designed online test to solve all your preparation worries. Go wherever you want to and practice whenever you want, using the online test platform.