On the subject of Anonymous classes, the Oracle documentation states that...
They are like local classes except that they do not have a name. Use them if you need to use a local class only once
Now, given that local classes are (to my knowledge) classes defined within a method (or some other local construct) like the following...(where 'MyInterface' is an interface with an abstract 'test' method)
public void localTest(){
MyInterface mi = new MyInterface(){
@Override
public void test(){System.out.println("test");};
};
}
The above is OK and falls within the definition above, however, I can also define the following...
class MyClass{
MyInterface mi = new MyInterface(){
@Override
public void test(){System.out.println("test");};
};
}
This isn't within a method so isn't a 'Local' class and therefore doesn't fall within the above definition. Is there anywhere I can read about these types of anonymous classes (anonymous member classes if you will). What exactly are they if not anonymous classes as defined?
void localTest()to returnMyInterfaceyou will just publish variable that references your anonymous class - even if the reference can be accessed outside your method. So the class is still anonymous - it's local as you cannot have any other instances of this class. So the class is local (the object not necessary)