wood burning stoves 2.0*
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
Author

Anonymous Class(Only used for overriding?)

Paul Callaly
Greenhorn

Joined: Dec 16, 2003
Posts: 12
Hi
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.
Paul
Sirish Kumar
Greenhorn

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();}
};
anonymous.superClassMethod();
// Compile time error since new method cannot be invoked
//anonymous.anonymousClassMethod();
}
}
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: http://aspose.com/file-tools
 
subject: Anonymous Class(Only used for overriding?)