0

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.

  • It's "stored" in the overridden `toString` method. – Elliott Frisch Feb 23 '20 at 19:25
  • Each time that constructor is called, Java makes a copy of `o` which will be used by the anonymous implementation of Printable which your code creates in that constructor. In fact, `o` needs to be either final or effectively final (that is, never reassigned a value) for this to work, so that the copy is reliable. – VGR Feb 23 '20 at 19:47

0 Answers0