BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Java – private constructor example

Last Updated: September 11, 2022 by Chaitanya Singh | Filed Under: java

The use of private constructor is to serve singleton classes. A singleton class is one which limits the number of objects creation to one. Using private constructor we can ensure that no more than one object can be created at a time. By providing a private constructor you prevent class instances from being created in any place other than this very class. We will see in the below example how to use private constructor for limiting the number of objects for a singleton class.

Example of Private Constructor

public class SingleTonClass {
   //Static Class Reference
   private static SingleTonClass obj=null;
   private SingleTonClass(){
      /*Private Constructor will prevent 
       * the instantiation of this class directly*/
   }
   public static SingleTonClass objectCreationMethod(){
	/*This logic will ensure that no more than
	 * one object can be created at a time */
	if(obj==null){
	    obj= new SingleTonClass();
	}
        return obj;
   }
   public void display(){
	System.out.println("Singleton class Example");
   }
   public static void main(String args[]){
	//Object cannot be created directly due to private constructor 
        //This way it is forced to create object via our method where
        //we have logic for only one object creation
	SingleTonClass myobject= SingleTonClass.objectCreationMethod();
	myobject.display();
   }
}

Output:

Singleton class Example

Top Related Articles:

  1. What is new Keyword in Java
  2. Final Keyword In Java – Final variable, Method and Class
  3. Method Overloading in Java with examples
  4. Java – Default constructor with example
  5. Constructor Overloading in Java with examples

Tags: Java-OOPs

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Comments

  1. Paru says

    April 6, 2015 at 3:25 AM

    Hi,
    when I tried the above example, I was able to instantiate the class using new keyword,
    i.e, SingleTonClass obj3=new SingleTonClass();

    I presumed this wud not be possible for a private Constructor.

    Pls advice if my assumption is wrong and why if that is the case.

    Thanks,
    Paru

    Reply
    • Daryll David says

      April 12, 2015 at 7:59 AM

      “SingleTonClass obj3=new SingleTonClass();” is inside the main method which is in the class SingleTonClass. Compilation succeeds because although it’s a private constructor, private members can be accessed within the class only.

      remove the main method from the SingleTonClass and create a separate .java file with main method and test “SingleTonClass obj3=new SingleTonClass();”

      Reply
      • omar says

        January 11, 2016 at 9:45 AM

        I was going to say that , thanks !

        Reply
    • Sandeep Saproo says

      August 17, 2017 at 1:46 PM

      private Constructor is used to prevent object creation outside the class.
      We can create more than one object in Singleton class.

      Reply
  2. Trinanjana says

    May 23, 2015 at 4:23 AM

    Can you please explain the difference between a static class and a singleton class?

    Reply
    • Ashir says

      August 18, 2015 at 1:27 PM

      The static class means that call the method without creating it instance of object. In static class you freely called the method without making refrernce of object but in same class you to do….
      The singleTOn class in which you have to follow the private constructor rule ..

      Reply
  3. Gautham says

    October 4, 2015 at 4:29 PM

    What is the use of not creating more than one object at a time? Does certain programs require them?

    Reply
    • karan says

      December 10, 2015 at 5:17 AM

      Yes, operations like print spooling etc would require the use of singleton pattern.

      Reply
  4. RAJ says

    October 8, 2015 at 7:08 PM

    I have created a child class “trial” and instead of creating objects from parent class, i am creating it from child class and i have created 3 objects.
    I think it should have given error by doing this?

    Reply
  5. Er.chandramohan says

    March 25, 2016 at 6:22 AM

    thank you sir but i need another best example for private constructor…i am using a private constructor in another class i can access a private constructor in main class

    Reply
  6. Hoan Nguyen says

    May 17, 2016 at 5:54 PM

    Dear guys,

    could you please explain to me the following code:

    ” private static SingleTonClass obj=null; ”

    Thank you in advance,
    Hoan

    Reply
    • Hau Nguyen says

      August 5, 2016 at 10:35 AM

      private static SingleTonClass obj=null;
      ↓
      1.private -> only this SingleTonClass can use it.
      2.static -> Because objectCreationMethod() use this variable “obj”. But, objectCreationMethod() is static method, so “obj” must be static.
      3.null ->
      – At the first time we call objectCreationMethod(), “obj” is null, then we create new object by this command:
      obj= new SingleTonClass(); (*)

      – The second time we call objectCreationMethod(), “obj” is NOT null because of above command (*).
      So, do not create new object, reuse the object which is created at the first time we called objectCreationMethod().
      – The same logic for n time calling objectCreationMethod(). There is one and only one object of SingleTonClass is created at the first time.
      This is why it is called SingleTon.

      Hope this help.

      Thanks,
      Hau Nguyen

      Reply
  7. swetha says

    May 30, 2016 at 2:23 PM

    what if we declare more than one constructor as private.I mean parameterised constructor..still we can create more than one instance..please provide some more clarity on private constructor

    Reply
  8. VallaDanger says

    August 15, 2016 at 9:59 PM

    Not thread-safe, violates singleton pattern. You either use Enum or double-check.

    Reply
  9. Pranav says

    July 20, 2017 at 1:33 PM

    i tried to make two objects at the same time, and i didn’t face any issue, objects got created and methods could be called easily … why so ??

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap