[Java] [Singleton Pattern] Why using Public classes with Private constructors?

We can find an example of a Public class with Private constructor below:

public class Products {

private static List<Product> listProducts = new ArrayList<Product>();
static {
for (int i = 0; i<19; i++) {
listProducts.add(new Producto(i, “producto ” + i));

private Products() {}


If we try to cast an instance of the class above we will obtain the following error:

GestionProductos example = new GestionProductos();

Error: The constructor GestionProductos() is not visible

So, how can we use this kind of class, and more important, why? well, the answer is simple. The designer has done the class in this way because he/she doesn’t want the class to be instanced. Although most of the times this behavior is a whimsy decission, it is a good practice for (like the class from the example above) a component delivered to a third, which is going to be forced to use only one instance from the class, avoiding unnecesary and memory spending copies from that class. For example, the class above is going to simulate the persistence layer, and we only want one copy of this layer,and the properties from the class are only accessible by the public setters and getters from the same class, like the following example:

List <Producto> listadoProducts = Products.getProducts();

This coding practice is called Singleton Pattern, or unique instance (the designers ensures that the class is going to be instanced only once).

Another use of a Public class with one private constructor could be, for example, to be instanced using other overloaded constructors, and these constructors would call the private constructor.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s