This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Question ID :953582884020 Which of these statements are true? Select 3 a) Non-static inner classes cannot have static members b) Objects of top level nested classes can be created without an instance of the outer class c) Member variables in any nested class cannot be declared final d) Anonymous classes cannot have constructors e) Anonymous classes cannot be static My answer - b) & d) I don't understand why JQPlus also choses e) as the right answer. I have read inner classes from Khalid Mughal & its very clearly given that we can have Anonymous Inner classes that are static. He has even given examples demonstrating the same... Can someone help, please !!!
I agree with Himanshu that a) is false. I think answer e) is correct. According to JLS 15.9.5 "An anonymous class is never abstract. An anonymous class is always an inner class; it is never static. An anonymous class is always implicitly final."
Tina JLS 15.9.5
Joined: Aug 01, 2001
Well! In that case, can we get Mr. Khalid Mughal to comment on this? Val, anyway, we can manage that ? I think I would stick with what JLS says. Waiting for your comments, Val. thanks - Himanshu
The best way to get the correct answers is to write a little piece of code for each option and see how it behaves. a. FALSE
Compiles fine. b. TRUE
compiles fine c. FALSE
compiles fine d. TRUE
Does not compile. The error is:
Which means that the compiler treats Runnable() as a method and not a constructor. e. This last one is tricky and the JLS and KM seems to be of different opinions. JLS says that anonymous classes cannot be declared static and KM says that an anonymous classes declared within a static context is implicitely static. Well, it is true that an anonymous class cannot be declared static. Moreover, an anonymous class is a local class, it is always created within the context of another method or initializer and there is no point in declaring a local method static even if the context is static. An anonymous class just serves the purpose of declaring and creating a instance of a class "on the fly". The result is always an instance of a class that can usually be returned. That object can be used anywhere in the program. It can be assigned to a static member or an instance member (see code below). Moreover an object is never static, it is the reference that points to it that can be static but not the object itself.