I got the below doubt when am surfing about Anonymous inner class
Here is the Original code I downloaded and was working around it (please refer to the below code only for my questions).
As per the link above they say we cannot overload & add additional methods in a Anonymous Inner class.
But When I compile the below it was working fine though I was not able to call those public methods outside the Inner class.
Initially I was surprised why I could not access the public methods outside the Inner class but then I realized the Object is being held by "father" class reference which does not know such function call.
What changes Can I make in the below code for making calls to the overloaded method and new Method outside the Inner class?
class TestAnonymous
{
public static void main(String[] args)
{
final int d = 10;
father f = new father(d);
father fAnon = new father(d){
// override method in superclass father
void method(int x){
System.out.println("Anonymous: " + x);
method("Anonymous: " + x); //This Compiles and executes fine.
newMethod(); //This Compiles and executes fine.
}
// overload method in superclass father
public void method(String str) {
System.out.println("Anonymous: " + str);
}
// adding a new method
public void newMethod() {
System.out.println("New method in Anonymous");
someOtherMethod(); //This Compiles and executes too.
}
};
//fAnon.method("New number"); // compile error
//fAnon.newMethod(); // compile error - Cannot find Symbol
}
public static final void someOtherMethod()
{
System.out.println("This is in Some other Method.");
}
} // end of ParentClass
class father
{
static int y;
father(int x){
y = x;
this.method(y);
}
void method(int x){
System.out.println("integer in inner class is: " +x);
}
}