Java – Private Constructor

In this article, we will learn and understand the need of private constructor in Java

1. Private constructor:

  • Private constructor prevents creating more than one object and also restricts outside classes to instantiate object
  • which infers object can be created only from inside of class and to get that object, outside classes invokes static utility method

Q) Where it is commonly used or explain scenario ?

Private constructor are most commonly used in below scenarios,

  • Classes containing only static utility methods
  • All constants in class (i.e.; public static final variables)
  • To prevent more than one object creation (Singleton design pattern)
  • To restrict compiler from inserting default no-arg constructor (when there exists no explicit constructor)
  • To utilize factory methods
  • enums for type-safety

1.1 Points to remember about private constructor:

  • Only one object instantiation is possible and that too in same class
  • Therefore, one object of that class is suppose to exist all time
  • Object cannot be created from outside of the class
  • To get that one instance, outside classes needs to invoke static method like getInstance()
  • In multi-threaded environment, multiple objects can be created using same getInsatnce() method
  • But again it can be restricted by adding keyword synchronized to getInstance() method

2. Example on private constructor

  • To demonstrate private constructor example, we will have a simple class making its constructor as private
  • Static field is declared to store this single instance and to get this instance from outside class we will implement static method which returns singleton instance every time

PrivateConstructorDemo.java

package in.bench.resources.constructor.example;

public class PrivateConstructorDemo {

	// static class reference
	private static PrivateConstructorDemo object = new PrivateConstructorDemo();

	// Prevents other classes from instantiating object of this class
	private PrivateConstructorDemo() {
		// empty private default no-arg constructor
		// Don't let anyone else instantiate this class
	}

	// static utility method to return singleton object
	public static PrivateConstructorDemo getInstance() {
		return object;
	}

	// display demo message
	public void printPrivateConstructorMsg() {
		System.out.println("Private constructor demo: Accessing method using singelton object");
	}
}

Explanation :

  • Here is the test class to invoke and get singleton object (main program)
  • Finally print message using singleton object

TestPrivateConstructor.java

package in.bench.resources.constructor.example;

public class TestPrivateConstructor {

	public static void main(String[] args) {

		PrivateConstructorDemo demo1 = PrivateConstructorDemo.getInstance();
		demo1.printPrivateConstructorMsg();
	}
}

Output:

Private constructor demo: Accessing method using singelton object

Explanation:

  • In above example, we are invoking print() method using object we got from static getInstance() method because direct object creation is not possible

Q) What happens, if we try to instantiate objects from outside of class ?

  • Compile-time error: The constructor PrivateConstructorDemo() is not visible
  • Solution: Don’t try to instantiate object of class that contains private constructor rather use static utility method like getInstance() to get singleton instance

PrivateConstructorDemo.java

1_Java_Private_Constructor_example

TestPrivateConstructor.java

2_Java_Private_Constructor_test_class_for_object_creation_not_possible

Q) What happens, if we extend the class containing private constructor ?

  • Compile-time error: Implicit super constructor PrivateConstructorDemo() is not visible for default constructor. Must define an explicit constructor
  • Solution: Don’t try to extend classes containing private constructor. We can get only singleton objects by invoking getInstance() method from this class and then accordingly we can invoke static or non-static utility methods of this class

PrivateConstructorDemo.java

1_Java_Private_Constructor_example

TestPrivateConstructor.java

3_Java_Private_Constructor_test_class_for_inheritance_not_possible

3. Example on Singleton design pattern (Lazy instantiation technique)

  • Here is the easiest and most commonly used singleton design pattern
  • This class create object upon demand i.e.; object is not created until and unless we invoke getInstance() method and this technique is known as lazy instantiation
  • This is done for the very first time and later when we invoke getInstance() –> directly instance is returned, as already instance created and available in the current context
  • This singleton design pattern ensures only one object is created and available at any given point of time

SingleTonDemo.java

package in.bench.resources.constructor.example;

public class SingleTonDemo {

	// static class reference
	private static SingleTonDemo instance = null;

	// Prevents other classes from instantiating object of this class
	private SingleTonDemo() {
		// empty private default no-arg constructor
		// Don't let anyone else instantiate this class
	}

	// static utility method to return singleton object
	public static SingleTonDemo getInstance() {

		if(instance == null) {
			// lazy initialization technique
			instance = new SingleTonDemo();
		}
		return instance;
	}

	// display demo message
	public void printPrivateConstructorMsg() {
		System.out.println("Lazy initialization technique: Accessing method using singelton instance");
	}
}

TestPrivateConstructor.java

  • Here is the test class to invoke and get singleton object (main program)
  • Finally print message using singleton object
package in.bench.resources.constructor.example;

public class TestPrivateConstructor {

	public static void main(String[] args) {

		SingleTonDemo demo2 = SingleTonDemo.getInstance();
		demo2.printPrivateConstructorMsg();
	}
}

Output:

Lazy initialization technique: Accessing method using singelton instance

Explanation:

  • Here too, we are invoking print() method using object we got from static getInstance() method because direct object creation is not possible
  • But instance created only once, when we invoke getInsatnce() for the very first time

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java - Static Constructor, a big interview question ?
Java - Method v/s Constructor