• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Anonymous Class(Only used for overriding?)

 
Paul Callaly
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 330
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic