This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
Q1: Can anonymous inner classes declare their own variables? If so, what modifiers can we give them? Q2: Can we define constructors for our abstract class and invoke them via call to super() from either a child class constructor or an anonymous subclass? Thanks!Taking the exam on the 21st of this month! Help!
Thinking is the talking of the soul with itself...-Plato
q1. Do you mean declaring fields that did not exist on the type an anonymous class extends or implements? I don't think so. An anonymous class does not declares a new type, now, how the new members would be accessed without a proper type? q2. Yes I think is OK. It is not possible to create an instance of an abstract class, but the initialization in its constructor may be applied to subtype instances. Notice: The answers could have been extracted by running examples. I have no a compiler at the moment.
SCJP2. Please Indent your code using UBB Code
Joined: Aug 16, 2003
Thank you, sir. I thought it would be legal for an anonymous class to declare a member variable of its own. But does it inherit its superclass' or interface's variables instead?
As a follow-up question to Mr. Botella: Sir, if an anonymous inner class can actually declare its own methods, why does the K&B book say it will generate a compiler error if you invoke a method not defined in your superclass or interface? It is also stated there that the main purpose of defining an inner class is overriding?
Originally posted by K Ville: As a follow-up question to Mr. Botella: Sir, if an anonymous inner class can actually declare its own methods, why does the K&B book say it will generate a compiler error if you invoke a method not defined in your superclass or interface? It is also stated there that the main purpose of defining an inner class is overriding?
It probably trying to say that you can not invoke those method from outside of the anonymous inner class. The reason is with anonymous class you basically lock(sign the contract) that say your anonymous object IS a specific class or interface, where the compiler will only recognized the method that were declared in those class or interface. It's not much different when you are dealing with non-anonymous class, when you have an instance of implementation object being define as its interface..you can't use any specific method not in the interface unless you manually cast it back. For example