Java/J2EE and SOA (349 Blogs) Become a Certified Professional
AWS Global Infrastructure

Programming & Frameworks

Topics Covered
  • C Programming and Data Structures (16 Blogs)
  • Comprehensive Java Course (5 Blogs)
  • Java/J2EE and SOA (346 Blogs)
  • Spring Framework (8 Blogs)
SEE MORE

How to Implement Private Constructor in Java

Last updated on Jun 17,2021 10.1K Views


Constructors are utilized to initialize an object’s state. Similar to methods, a constructor can also hold a collection of statements, which can be called nothing but instructions. In this article, we will discuss Private Constructor in Java in the following order:

 

Introduction to Constructor in Java

Constructors are executed at the time of object creation. To get a better understanding of the constructor and its applications, just think of a box as a class. A Box class is assumed to have some class variables (i.e. length, breadth, and height). However, at the time of creating its object (i.e. Box exists in computer’s memory), so can a box exist with no value defined for its dimensional quantities.

Obviously, no.

Hence, a constructor is introduced to assign values to class variables at object creation. This can be explicitly done by the programmer or by Java itself. When done by Java itself it is termed as a default constructor.

It is imperative to understand that any method, which possesses access specifier provided by the coder to the constructor, which is made private, can only be accessed inside the class itself.

Private Constructor in Java

 

Singleton Class

From the name itself, we can call a class a singleton if it restricts the number of objects of that class to one. A class cannot have more than one single object in such cases. The singleton classes are used exhaustively in concepts like networking and database connectivity. Singleton class is a private class.

There must be another way to extract the instance of the class and a return method to fetch back the result. Below is an apt illustration of the same. The first pictograph depicts the probable result where the value of “a.x” equates to 20 and the value of “b.x” results in 20 as well. In the code, while we define the singleton private class, the constructors of it cannot be accessed outside the class.

Value of a.x = 20

Value of b.x = 20

// 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); 
}	 
}

 

Impact of Private Constructor in Java

The private constructors cannot access derived classes from another class. Thus, we have to give a public function, which calls the private constructor. In case, the object is not initialized, or we have to send back an instance to the object if it was initialized. This is especially very useful for objects, which cannot be initialized. A private constructor is used in the following cases:

  • The respective classes, which have only static methods and members.
  • The specific classes, which have only widely used static final members (constants).
  • To incorporate singletons.
  • To incorporate the factory methods.

To utilize enumerations, which are type-safe.

 

Internal Constructor Chaining

Internal constructor chaining is when a constructor calls another constructor of the same class then it can be referred to as constructor chaining. It is our duty to use this keyword to call another constructor of the class. In some instances, it is used to define some default values of the class variables. Please also keep in mind that another constructor call must be the first statement in the code block.

In addition, there should not be recursive calls, which will create an infinite loop. Let us now have a look at an example of a constructor chaining in java program.

package com.journaldev.constructor;
public class Employee {
	private int id;
	private String name;
	public Employee() {
		this("John Doe", 999);
		System.out.println("Default Employee Created");
	}
	public Employee(int i) {
		this("John Doe", i);
		System.out.println("Employee Created with Default Name");
	}
	public Employee(String s, int i) {
		this.id = i;
		this.name = s;
		System.out.println("Employee Created");
	}
	public static void main(String[] args) {
		Employee emp = new Employee();
		System.out.println(emp);
		Employee emp1 = new Employee(10);
		System.out.println(emp1);
		Employee emp2 = new Employee("Pankaj", 20);
		System.out.println(emp2);
	}
	@Override
	public String toString() {
		return "ID = "+id+", Name = "+name;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}

 

 

Singleton Class Design Pattern

Singleton-Design-Pattern

 

  • Class-level Member (Eager Initialization Method):

  1. First, make a private constant static instance of a singleton class.

  2. Then, write a static method, which returns the object of a singleton class, which we created as a class-member instance.

  3. It is possible to mark a static member as the public to access constant static instance directly.

  4. The singleton class varies from a normal Java class in terms of instantiation. In a normal class, a constructor is used but for singleton class we use the get Instance () method.

 

  • Class-level Member (Lazy Initialization Method):

  1. First, initiate a constructor as private.

  2. Then create a private static instance of this singleton class. Keep in mind to NOT instantiate it.

  3. Then, write a static method, which checks the static instance member for null and initiates the instance. Finally, it returns an object of the singleton class.

 

  • The Class-level Member (Lazy Initialization with double lock Method):

Consider two threads running where both get inside the “if” statement concurrently while the instance is null. Where, one thread goes into a synchronized block to create an instance, while the other is blocked. As the first thread resides in the synchronized block, the thread in the queue creates another singleton object. Please note that as the second thread enters a synchronized block, it fails to check if the instance is non-null.

 

  • Using nested Inner class (Lazy Load method):

Here, it is based on Java Language Specifications (JLS). The Java Virtual Machine loads static data-members only on-demand. Thus, the Singleton class loads first by the JVM. Hence, there is no static data member in a class;

The Singleton Class Holder does not load SINGLE_INSTANCE. When we invoke getIntance method, only this occurs. JLS guarantees the execution of the class’s initialization. A provision for explicit synchronization on static getInstance() method for loading and initialization. As the initialization creates the static variable SINGLE_INSTANCE in a sequential way, all the concurrent invocations of the getInstance() will come back the same without synchronization overhead.

 

  • By using Enums

Not all the above approaches are complete solutions in all cases. Multiple instances of the above implementations can be created by using reflection. In both scenarios, we can bypass the private constructor and create multiple instances. Therefore, a new approach is to create a singleton class by using enums. As enums fields are compiled time constants, they are instances of their enum type. They are constructed when enum type is referenced for the first time.

With this, we come to the end of Private Constructor in Java article. I hope you got an understanding of Private Constructors and how they can be used in Java.

Check out the Java Online Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Edureka’s Java J2EE and SOA training and certification course is designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this “Java Tutorial” blog and we will get back to you as soon as possible.

Upcoming Batches For Java Course Online
Course NameDateDetails
Java Course Online

Class Starts on 1st March,2025

1st March

SAT&SUN (Weekend Batch)
View Details
Comments
0 Comments

Join the discussion

Browse Categories

webinar REGISTER FOR FREE WEBINAR
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP

Subscribe to our Newsletter, and get personalized recommendations.

image not found!
image not found!

How to Implement Private Constructor in Java

edureka.co