The Wayback Machine - https://web.archive.org/web/20240619235939/https://www.geeksforgeeks.org/private-constructors-and-singleton-classes-in-java/
Open In App

Private Constructors and Singleton Classes in Java

Last Updated : 21 Jun, 2018
Improve
Improve
Like Article
Like
Save
Share
Report

Let’s first analyze the following question:

Can we have private constructors ?

As you can easily guess, like any method we can provide access specifier to the constructor. If it’s made private, then it can only be accessed inside the class.

Do we need such ‘private constructors ‘ ?

There are various scenarios where we can use private constructors. The major ones are

  1. Internal Constructor chaining
  2. Singleton class design pattern

What is a Singleton class?

As the name implies, a class is said to be singleton if it limits the number of objects of that class to one.

We can’t have more than a single object for such classes.

Singleton classes are employed extensively in concepts like Networking and Database Connectivity.

Design Pattern of Singleton classes:

The constructor of singleton class would be private so there must be another way to get the instance of that class. This problem is resolved using a class member instance and a factory method to return the class member.

Below is an example in java illustrating the same:




// Java program to demonstrate implementation of Singleton 
// pattern using private constructors.
import java.io.*;
  
class MySingleton
{
    static MySingleton instance = null;
    public int x = 10;
    
    // private constructor can't be accessed outside the class
    private MySingleton() {  }
   
    // Factory method to provide the users with instances
    static public MySingleton getInstance()
    {
        if (instance == null)        
             instance = new MySingleton();
   
        return instance;
    
}
  
// Driver Class
class Main
{
   public static void main(String args[])    
   {
       MySingleton a = MySingleton.getInstance();
       MySingleton b = MySingleton.getInstance();
       a.x = a.x + 10;
       System.out.println("Value of a.x = " + a.x);
       System.out.println("Value of b.x = " + b.x);
   }    
}


Output:

Value of a.x = 20
Value of b.x = 20

We changed value of a.x, value of b.x also got updated because both ‘a’ and ‘b’ refer to same object, i.e., they are objects of a singleton class.



Previous Article
Next Article

Similar Reads

private vs private-final injection of dependency
Dependency Injection (DI) is essential for improving code modularity, maintainability, and testability in the context of sophisticated Java programming. Choosing between private and private-final injection for dependencies is a typical DI concern. We will examine the distinctions between these two strategies in this post, as well as their applicati
5 min read
Singleton and Prototype Bean Scopes in Java Spring
Bean Scopes refers to the lifecycle of Bean that means when the object of Bean will be instantiated, how long does that object live, and how many objects will be created for that bean throughout. Basically, it controls the instance creation of the bean and it is managed by the spring container.Bean Scopes in Spring The spring framework provides fiv
8 min read
Advantages and Disadvantages of using Enum as Singleton in Java
Enum Singletons are new ways of using Enum with only one instance to implement the Singleton pattern in Java. While there has been a Singleton pattern in Java for a long time, Enum Singletons are a comparatively recent term and in use since the implementation of Enum as a keyword and function from Java 5 onwards. Advantages of using Enum as Singlet
3 min read
Difference Between Singleton Pattern and Static Class in Java
Singleton Pattern belongs to Creational type pattern. As the name suggests, the creational design type deals with object creation mechanisms. Basically, to simplify this, creational pattern explains to us the creation of objects in a manner suitable to a given situation. Singleton design pattern is used when we need to ensure that only one object o
6 min read
Difference Between Singleton and Factory Design Pattern in Java
Design patterns are essential tools for creating maintainable and scalable software. Two commonly used design patterns in Java are the Singleton and Factory patterns. This article provides an introduction to the Singleton and Factory design patterns with examples. Singleton Design Pattern in JavaThe Singleton pattern is a creational design pattern
3 min read
Java Program to Demonstrate the Nested Initialization For Singleton Class
A Singleton Class is capable of producing just a single instance. Every Singleton class has a getInstance method which returns its object. When the getInstance method is called for the first time, an object of the class is generated, stored, and then returned. On subsequent calls to getInstance, the same object generated earlier gets returned. Nest
4 min read
Java Program to Demonstrate the Double-Check Locking For Singleton Class
One of the key challenges faced by junior developers is the way to keep Singleton class as Singleton i.e. the way to prevent multiple instances of Singleton class. Double checked locking of Singleton is a way to make sure that only one instance of Singleton class is created through an application life cycle. In double-checked locking, code checks f
3 min read
Singleton Method Design Pattern in Java
In object-oriented programming, a java singleton class is a class that can have only one object (an instance of the class) at a time. After the first time, if we try to instantiate the Java Singleton classes, the new variable also points to the first instance created. So whatever modifications we do to any variable inside the class through any inst
8 min read
Collections.singleton() method in Java with example
java.util.Collections.singleton() method is a java.util.Collections class method. It creates a immutable set over a single specified element. An application of this method is to remove an element from Collections like List and Set. Syntax: public static Set singleton(T obj) and public static List singletonList(T obj) Parameters: obj : the sole obje
3 min read
Java Singleton Design Pattern Practices with Examples
In previous articles, we discussed about singleton design pattern and singleton class implementation in detail. In this article, we will see how we can create singleton classes. After reading this article you will be able to create your singleton class according to your requirement, which is simple and without bottlenecks. There are many ways this
6 min read
Article Tags :
Practice Tags :