What is a java statement
Depending on the usage, there are several "correct" answers.
Since java5 the best way to do it is to use an enum:
Pre java5, the most simple case is:
Let's go over the code. First, you want the class to be final. In this case, I've used the final keyword to let the users know it is final. Then you need to make the constructor private to prevent users to create their own Foo. Throwing an exception from the constructor prevents users to use reflection to create a second Foo. Then you create a private static final Foo field to hold the only instance, and a public static Foo getInstance() method to return it. The Java specification makes sure that the constructor is only called when the class is first used.
When you have a
very large object or heavy construction code AND also have other accessible static methods or fields that might be used before an instance is needed, then and only then you need to use lazy initialization.
You can use a private static class to load the instance. The code would then look like:
Since the line private static final Foo INSTANCE = new Foo(); is only executed when the class FooLoader is actually used, this takes care of the lazy instantiation, and is it guaranteed to be thread safe.
When you also want to be able to serialize your object you need to make sure that deserialization won't create a copy.
The method readResolve() will make sure the only instance will be returned, even when the object was serialized in a previous run of your program.Source: stackoverflow.com