How to Create a Singleton Object

This example shows how to create a singleton object. A singleton is a class of which there can only be one instance in the same Java Virtual Machine.
To create a singleton there has to be a private constructor because the class will itself control the one and only instance that will be created, and of course a private constructor cannot be called from outside the class.
Instead, a method is created with public access that returns the singleton instance (if the method is called the first time the object is instantiated). The example class MySingleton illustrates this:

No matter how many times the method createMySingleton() is called, it will always return a reference to the same singleton object.
This code illustrates this by calling the method twice and then compare the two references. The output of the code is ‘true’ since they both point to the same singleton object.

Search for more Java info on this site here:
Custom Search

Please type any questions here.