I have been looking at Java for some months now, but I struggle to understand the following example:
public class UnderstandAnonymousInterfaceInstance {
private interface Printable {
public void print();
}
private Printable printer;
private UnderstandAnonymousInterfaceInstance(Object o) {
this.printer = new Printable() {
@Override
public void print() {
System.out.println("" + o.toString());
}
};
}
void print() {
this.printer.print();
}
public static void main(String[] args) {
new UnderstandAnonymousInterfaceInstance(new Object() {
@Override
public String toString() {
return "My Teststring";
}
}).print();
}
}
Output is
My Teststring
But why? Where is the handle to the Object stored? The interface does not have any members of course neither does anybody else in this example. The handle to Object is passed to the constructor and on to the anonymous instance of the interface. From my understanding, it should cease to exist afterwards and I am expecting a nullpointer exception, when print() is called.
Thanks in advance for any help.