Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Private Constructors
3.
Singleton Class
4.
Frequently Asked Questions
5.
Conclusion
Last Updated: Mar 27, 2024

Private Constructors and Singleton Classes in Java

Author Pradeep Kumar
0 upvote
Roadmap to SDE career at Amazon
Speaker
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM

Introduction

In this blog, we will look into Private Constructors and Singleton Classes in Java. A singleton class is one that can only have one object at any one time. We'll go through how to create a singleton class in Java and how to use private constructors in singleton classes.

If you are new to Java and are yet to write your first program in the language, you can check out this article to get started with the language.

Must recommended topic   Iteration Statements in Java and Hashcode Method in Java

Private Constructors

In Java, you can declare a constructor as private. By declaring the constructor of a class as private, you can not create an object of that class. To declare the constructor as private, you can use the private access specifier. We generally use a private constructor in a Singleton class.

Syntax:

class class_name {
    // body of the class

    // declaring the constructor as private
    private class_name(){
        // Code for the constructor
    } 
}

Must Read Conditional Statements in Java and Swap Function in Java.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Singleton Class

A singleton class is one that can only have one object (a class instance) at a time. When we try to instantiate the Singleton class again, the new variable also points to the initial instance produced. As a result, any changes we make to any variable within the class through any instance affect the variable of the single instance produced, which can be seen if we access that value through any variable of the class type stated. We use a private constructor in a singleton class. For example,

Main.java

// Singleton Class
class SingletonClass
{
    private static SingletonClass class_instance = null;
    public String s = "Initial Value";
   
    // private constructor
    private SingletonClass () {}
   
    // method to get the instance of the class
    static public SingletonClass getClassInstance()
    {
        if (class_instance == null){
            class_instance = new SingletonClass ();
            return class_instance;
        }        
        else{
            return class_instance;
        }  
    }
}
 
// Main Class
class Main
{
   public static void main(String args[])    
   {
        SingletonClass first_instance = SingletonClass.getClassInstance();
        SingletonClass second_instance = SingletonClass.getClassInstance();
            //print the value of s from both instances
        System.out.println("value of s in first_instance: " + first_instance.s + " and value of s in second_instance is: " + second_instance.s);
        //now change the value of s in first_instance
        first_instance.s = "Changed Value";
        //now print the value of string from both the instances again
        System.out.println("value of s in first_instance: " + first_instance.s + " and value of s in second_instance is: " + second_instance.s);
   }    
}

Output:

value of s in first_instance: Initial Value and value of s in second_instance is: Initial Value
value of s in first_instance: Changed Value and value of s in second_instance is: Changed Value

As you can see from the output, upon changing the value of variable 's' in one instance, the value changes in another instance as both instances are pointing to one object. Try this code by yourself on Online Java Compiler.

You can also read about the Multiple Inheritance in Java.

Frequently Asked Questions

1. Where is the concept of Singleton class mostly used?
Ans: In concepts like networking and database connectivity, singleton classes are frequently used.

2. Can a Singleton class have a public Constructor?
Ans: If a class has a public constructor, then by definition, anybody can create an instance of it at any time, so it can't be a singleton.

3. Why is the instance member of a Singleton class declared static?
Ans: The instance field contains the unique reference to the single instance of the Singleton class. Because its scope must be the class itself and not a specific instance, it is stored in a static variable.

Conclusion

In this article, we have extensively discussed the Singleton class of JavaWe discussed how we could declare and use a singleton class in Java. Additionally, we looked at private constructors in Java.

We hope that this blog has helped you enhance your knowledge regarding the Singleton class and Private Constructors, and if you like to learn more, check out our article on Writer Class. And to learn in-depth about android development, check out our Android Development course on the Coding Ninjas website. Do upvote our blog to help other ninjas grow. Happy Coding!

Previous article
Method Overloading and Method Overriding
Next article
Java Destructor
Live masterclass