a
there is a reference to the newly created object that new A()
creates. That has nothing to do with the singleton pattern, though; that's always true.
In the singleton pattern, you would find a way of ensuring that new A()
is only called once ever in the program. The typical way this is done is to make A
's constructor private, and create the instance from within A
(which is thus the only class allowed to call the private constructor).
public class A {
public static final A instance = new A();
private A() {}
}
This approach does have a few edge cases, though: you can create extra instances through reflection, and through serialization if A
is serializable. To really make a singleton, the best way in Java is to use enums:
public enum A {
INSTANCE;
// fields, methods etc go here
}
The JVM will ensure that only one A.INSTANCE
exists in the process.