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