Hello! I'm trying to learn about anonymous inner classes and can't seem to find a way to call a method that I defined inside the anonymous class from outside of it, even though overriding seems to work perfectly fine. Calling the method from inside the anonymous class (through the initializer) als works fine.
Code:
void print() {
System.out.println("I'm extended");
}
}
public class CursedOriginal {
//Declare and instantiante anonymous class
static ExtendedByAnonymous object = new ExtendedByAnonymous() {
//Initialization Block
{
System.out.println("anonymous object created");
anonprint();
}
@Override
void print() {
System.out.println("overriden print");
}
void anonprint() {
System.out.println("anonymous print");
}
};
public static void main(String[] args) {
System.out.println("in main");
object.print();
object.anonprint(); //Cannot resolve method 'anonprint' in 'ExtendedByAnonymous'
}
}
/*
OUTPUT (without object.anonprint();)
anonymous object created
anonymous print
in main
overriden print
*/```
It seems like the compiler is trying to find the method by looking in the ExtendedByAnonymous class, even though, as far as I know, the creation of an anonymous inner class is supposed to generate a new class that simply extends ExtendedByAnonymous, and then create an instance of that new class. Instead of realizing that ```object``` refers to that generated class, it seems to think that it's a reference to an object of ExtendedByAnonymous.
Is my thinking incorrect? If not, why is the compiler not finding the ```anonprint``` method?