Careers360 Logo
Exploring Private Constructor In Java

Exploring Private Constructor In Java

Edited By Team Careers360 | Updated on Feb 07, 2024 09:55 AM IST | #Java

In Java, constructors play a crucial role in the instantiation of objects. Private constructors in Java are unique methods that are invoked during the creation of an object, playing a pivotal role in initialising the object's state. While constructors are typically public, there are scenarios where a private constructor is beneficial.

There are situations where limiting direct access to the constructor becomes advantageous. This limitation is achieved by declaring a constructor as private. In this article, we will explore what a private constructor in Java is, use of private constructor in Java, and provide examples to illustrate its applications. But before starting the preparation regarding swapping, consider learning these Java certification courses.

What is a Private Constructor in Java?

A private constructor in Java is a constructor with the private access modifier. Unlike public constructors, private constructors cannot be accessed directly from outside the class. This means that objects of the class cannot be created using the new keyword outside the class.

The primary purpose of a private constructor in Java is to control the instantiation of objects and restrict access to the constructor, ensuring that objects can only be created in specific ways defined within the class itself. Here is an example:

public class SingletonExample {

private static SingletonExample instance;


// Private constructor to prevent instantiation from outside the class

private SingletonExample() {

// Initialization of the code

}


// Public method to provide a global point of access

public static SingletonExample getInstance() {

if (instance == null) {

instance = new SingletonExample();

}

return instance;

}


public void displayMessage() {

System.out.println("Hello, This is an example of a singleton instance!");

}


public static void main(String[] args) {

// The following line will not work because the constructor is private

// SingletonExample obj = new SingletonExample();


// Access the instance using the public method

SingletonExample obj = SingletonExample.getInstance();

obj.displayMessage();

}

}

Also Read:

Uses of Private Constructor in Java

A private constructor is a constructor method that is declared with the "private" access modifier, restricting its visibility to only within the class itself. Primarily, it empowers developers to control the instantiation process of a class, preventing external entities from creating objects directly.

This control facilitates the implementation of various design patterns, such as the Singleton pattern, and enhances encapsulation, ensuring that the internal state of a class remains encapsulated and accessible only through well-defined interfaces. The following points highlights the use of private constructor in Java:

1. Singleton Design Pattern

One of the most common use cases for a private constructor in Java is in implementing the Singleton design pattern. In the Singleton pattern, a class has only one instance, and a private constructor ensures that no other class can create instances of it.

public class Singleton {

private static Singleton instance;


private Singleton() {

// private constructor

}


public static Singleton getInstance() {

if (instance == null) {

instance = new Singleton();

}

return instance;

}

}


2. Utility Classes

Private constructor in Java is also used in utility classes, where the class contains only static methods and should not be instantiated. By providing a private constructor, you prevent accidental instantiation of the utility class.


public class MathUtils {

private MathUtils() {

// private constructor

}


public static int add(int a, int b) {

return a + b;

}

public static int multiply(int a, int b) {

return a * b;

}

}

3. Factory Methods

Private constructors can be used in conjunction with public static factory methods to control the creation of objects and provide a more meaningful way to create instances.

public class Car {

private String model;


private Car(String model) {

this.model = model;

}


public static Car createCar(String model) {

// Additional logic if needed

return new Car(model);

}

public String getModel() {

return model;

}

}

Also Read:

Examples of Private Constructor in Java

A private constructor in Java is a crucial concept in object-oriented programming that plays a pivotal role in controlling the instantiation of a class. Exploring examples of private constructors in Java reveals their significance in achieving robust and secure object-oriented designs.

Example 1: Singleton Pattern

The Singleton Pattern is a fundamental design pattern in software engineering, belonging to the creational pattern category. It is employed to ensure that a class has only one instance and provides a global point of access to that instance. The following showcases the example of singleton pattern:

public class AppConfig {

private static AppConfig instance;

private AppConfig() {

// private constructor

}


public static AppConfig getInstance() {

if (instance == null) {

instance = new AppConfig();

}

return instance;

}

}

Example 2: Utility Class

Utility classes play a crucial role in providing reusable and common functionality across an application. These classes, often designed to encapsulate a set of static methods or functions, serve as a repository for tools and functionalities that are not inherently tied to specific objects or instances. The utility class presented in Example 2 exemplifies the concept of a versatile and efficient code container.

public class StringUtils {

private StringUtils() {

// private constructor

}


public static boolean isNullOrEmpty(String str) {

return str == null || str.isEmpty();

}

}

Also Read:

Example 3: Factory Method

In Example 3 the concept of a Factory Method within the context of Java, exploring how it complements a private constructor to control the creation of objects. This example will shed light on the practical implementation of Factory Methods, illustrating their utility in crafting instances of a class while encapsulating the underlying instantiation logic.


public class Book {

private String title; // A class to collect the books title


private Book(String title) {

this.title = title; //adding the title here

}


public static Book createBook(String title) {

// Additional logic if needed

return new Book(title);

}


public String getTitle() {

return title;

}

}

Related: Popular Java Certification Courses by Top Providers

Conclusion

Private constructors in Java offer a powerful mechanism to control the instantiation of objects within a class. By using private constructors, developers can enforce design patterns, encapsulate object creation logic, and enhance the overall maintainability of their code. Understanding when and how to use private constructors is an important aspect of effective Java programming to become an effective Java programmer.

Frequently Asked Questions (FAQs)

1. What is a private constructor in Java?

In Java, a private constructor is a constructor with the private access modifier. It restricts access to the constructor from outside the class, preventing direct instantiation of objects using the new keyword.

2. Why would you use a private constructor in Java?

Private constructors are used for various purposes, including implementing design patterns such as Singleton, creating utility classes, and controlling object creation through factory methods.

3. Give a Private Constructor In Java Example.

A private constructor in Java is commonly used in the Singleton pattern. In this pattern, the class has a private constructor to prevent external instantiation, ensuring that only one instance of the class can exist.

4. Can a constructor be private in Java?

Yes, a constructor can be private in Java. Declaring a constructor as private restricts its access, preventing direct instantiation of objects from outside the class.

5. How to call private constructor in Java

In Java, it is not possible to directly call a private constructor from outside the class. Private constructors are designed to restrict instantiation to within the class itself, preventing external access.

Articles

Have a question related to Java ?
Udemy 53 courses offered
Eduonix 16 courses offered
Coursera 12 courses offered
Duke University, Durham 10 courses offered
Edx 10 courses offered
Back to top