This question already has an answer here:
I wrote the following code to implement the Singleton pattern:
public final class Test {
static final class TestHolder {
private static final Test INSTANCE = new Test();
}
private Test() {}
public static Test getInstance() {
return TestHolder.INSTANCE;
}
}
When I compile this file, it should generate Test.class and Test$TestHolder.class, but it also generates Test$1.class. This doesn't make sense. So why and how would this be?
Class
TestHolder
needs to call the private constructor inTest
. But it's private, and can't actually be called from another class. So the compiler plays a trick. It adds a new non-private constructor toTest
which only it knows about! That constructor takes an (unused) instance of this anonymous classTest$1
-- which nobody knows exists. ThenTestHolder
creates an instance ofTest$1
and calls that constructor, which is accessible (it's default-protected.)You can use
javap -c Test
(andjavap -c Test\$1
, andjavap -c Test\$TestHolder
) to see the code. It's quite clever, actually!