File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Anonymous Class(Only used for overriding?) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Anonymous Class(Only used for overriding?)" Watch "Anonymous Class(Only used for overriding?)" New topic

Anonymous Class(Only used for overriding?)

Paul Callaly

Joined: Dec 16, 2003
Posts: 12
If you define a method within an anonymous Class can you ever invoke it? It seems (from what I've read so far) that Anonymous classes can only be used to override methods Like in Listeners() and the like.
Sirish Kumar

Joined: Jan 28, 2004
Posts: 15
Hi Paul,
No it is not possible to invoke any new methods or access fields that have been declared inside the anonymous class. We can however declare new fields and methods though and the complier would not complain. But this would not be of much help
Anonymous classes do not have a name. So the only way to access the members is through the superclass or the superinterface reference. This being the case, there is no way one can invoke new methods and fields that have been added in the anonymous class(One can however invoke the new methods or access the new fields from within the methods of the superclass though)
Have a look at the example below

class SuperClass
int superClassVar = 1;
void superClassMethod()
System.out.println("superClassVar : " +superClassVar);
public class Anonymous
public static void main(String []a)
SuperClass anonymous = new SuperClass ()
//new field
int anonymousClassVar = 10;
//new method
void anonymousClassMethod()
System.out.println("anonymousClassVar : "+ anonymousClassVar);
//inherited method
void superClassMethod(){super.superClassMethod();//invoke the new method from the inherited methodanonymousClassMethod();}
// Compile time error since new method cannot be invoked
Hope that helps
dennis zined
Ranch Hand

Joined: Mar 07, 2003
Posts: 330
If you define a method within an anonymous Class can you ever invoke it?

Hi all. On the question "can you ever invoke it?"...i'd say yes. Please see code below.

How about new fields?....i'd say yes too. Please see code below:

As you can see in the examples above, you can only invoke a new member field or method once but not both on the same anonymous class.
In what scenario would this type of code above be useful....i dont know.
[ January 29, 2004: Message edited by: dennis zined ]

SCJP 1.4<br />SCWCD 1.4
I agree. Here's the link:
subject: Anonymous Class(Only used for overriding?)
It's not a secret anymore!