Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

Private Constructor in Java: Introduction

Updated on 20 November, 2024

57.85K+ views
13 min read

In Java, constructors are special methods used to initialize objects of a class. Like methods, constructors can also have access specifiers such as publicprotecteddefault, and private. A private constructor is a constructor that is accessible only within the class it is defined in.

Can a constructor be private?
Yes, a constructor can be private. When declared private, it restricts the instantiation of the class to within the class itself. This means that no object of the class can be created directly from outside the class.

Let’s take a closer look at the rules, use cases, and practical examples to understand how private constructors work in Java.

Check out our free courses to get an edge over the competition.

What is a Private Constructor in Java? 

A private constructor is a special type of constructor in Java that restricts the creation of objects from outside the class. It is often used to control how and when objects of a class are created or to prevent object creation altogether in certain cases.

When to Use Private Constructors

  • Utility Classes: Prevent object creation when only static methods are required.
  • Singleton Classes: Ensure that only one instance of a class exists.
  • Controlled Object Creation: Restrict instantiation within the class itself for specific control.

Code Example: Private Constructor in a Utility Class

Create a utility class that provides static methods for mathematical operations like addition and subtraction. Ensure no objects of the utility class can be created.

java

// Utility class for mathematical operations
class MathUtils {

    // Private constructor to prevent object creation
    private MathUtils() {
        throw new UnsupportedOperationException("Cannot instantiate MathUtils");
    }

    // Static method for addition
    public static int add(int a, int b) {
        return a + b;
    }

    // Static method for subtraction
    public static int subtract(int a, int b) {
        return a - b;
    }
}

public class Main {
    public static void main(String[] args) {
        // Accessing static methods without creating an object
        int sum = MathUtils.add(7, 3);
        int difference = MathUtils.subtract(10, 4);

        // Output the results
        System.out.println("Sum: " + sum);
        System.out.println("Difference: " + difference);

        // Uncomment the following code to see the error
        // MathUtils utils = new MathUtils();
    }
}

Output

Sum: 10
Difference: 6

Steps to Run the Code

  1. Copy the code into a Java IDE or text editor.

  2. Save the file as Main.java (or use the appropriate class name if you change it).

  3. Compile the file using javac Main.java.

  4. Run the program using java Main.

Explanation

  1. Private Constructor: The constructor in MathUtils is declared private, ensuring that no class object can be created.
  2. Static Methods: The class contains only static methods for mathematical operations, which can be accessed directly using the class name.
  3. Error Prevention: Uncommenting the line MathUtils utils = new MathUtils(); would result in a compile-time error, as the constructor is private.

Purpose of Private Constructors in Java

Private constructors in Java are needed to control object creation, promote encapsulation, and support specific design patterns. They allow developers to restrict how and when a class is instantiated, which makes them a significant tool in organized and efficient coding practices.

Why Use Private Constructors?

  • Encapsulation of Object Creation:
    • Limits instantiation to within the class.
    • Ensures that object creation follows specific rules, maintaining consistency.
  • Utility and Helper Classes:
    • Prevents instantiation for classes containing only static methods or constants.
    • Promotes reusable and organized code without unnecessary objects.
  • Design Patterns:
    • Singleton Pattern: Ensures only one instance of a class exists throughout the application.
    • Builder Pattern: Manages controlled and flexible object creation.

For instance, they help maintain the integrity of Singleton classes or prevent the creation of objects for utility classes that only provide static methods. This enhances code reliability and ensures adherence to best practices in Java development.

Check out all the Trending Java Tutorial Topics in 2024.

Rules for Private Constructors in Java 

Private constructors in Java are powerful tools for controlling how and when a class is instantiated. They follow specific rules to ensure restricted access and proper use in certain scenarios like design patterns and utility classes.

1. Singleton Pattern

The Singleton pattern ensures that a class has only one instance throughout the application. It is particularly useful for managing shared resources like database connections, configuration settings, or logging.

A private constructor ensures that no external class can create additional instances. Instead, a static method is provided to return the sole instance. The class also typically includes lazy or eager initialization to ensure efficient resource use.

Code:

Create a Logger class to handle logging throughout the application, ensuring only one instance exists for centralized logging.

java

// Singleton Logger class implementation
class Logger {
    private static Logger instance;

    // Private constructor to prevent direct instantiation
    private Logger() {
        System.out.println("Logger Instance Created");
    }

    // Static method to return the single instance
    public static Logger getInstance() {
        if (instance == null) {
            instance = new Logger();
        }
        return instance;
    }

    // Method to log messages
    public void log(String message) {
        System.out.println("Log: " + message);
    }
}

public class Main {
    public static void main(String[] args) {
        // Accessing the Singleton Logger instance
        Logger logger1 = Logger.getInstance();
        Logger logger2 = Logger.getInstance();

        // Logging messages
        logger1.log("Starting the application...");
        logger2.log("Loading resources...");

        // Verifying that both references point to the same instance
        System.out.println(logger1 == logger2); // true
    }
}

Output

Logger Instance Created
Log: Starting the application...
Log: Loading resources...
true

Explanation

  1. Private Constructor:
    • Prevents external instantiation, ensuring only one instance exists.
  2. Static Method (getInstance):
    • Creates the instance if it doesn’t exist and returns the same instance for every call.
  3. Shared Access:
    • logger1 and logger2 refer to the same instance, demonstrated by logger1 == logger2.
  4. Real-World Use Case:
    • In large applications, a singleton logger ensures consistent and centralized logging of application events without creating multiple logger instances.

2. Utility Classes

Utility classes provide reusable static methods or constants (e.g., MathCollections). These classes do not require instantiation. A private constructor enforces this by preventing object creation, signaling that the class is purely functional.

Code:

Problem Statement:
Create a utility class to provide mathematical operations without allowing object instantiation.

java

// Utility class with static methods
class MathUtils {
    // Private constructor to prevent instantiation
    private MathUtils() {
        throw new UnsupportedOperationException("Cannot instantiate MathUtils");
    }

    public static int add(int a, int b) {
        return a + b;
    }

    public static int subtract(int a, int b) {
        return a - b;
    }
}

public class Main {
    public static void main(String[] args) {
        // Using static methods directly
        System.out.println("Sum: " + MathUtils.add(5, 3));
        System.out.println("Difference: " + MathUtils.subtract(10, 4));

        // Uncommenting this line will cause a compile-time error
        // MathUtils utils = new MathUtils();
    }
}

Output:

Sum: 8
Difference: 6

Explanation:
The private constructor prevents object creation. Attempting to instantiate the class results in an exception, while static methods remain accessible.

Our learners also read: Free Java course!

3. Factory Method Pattern

In the Factory Method pattern, object creation is controlled via factory methods, which return instances of a class. The constructor is private to restrict direct instantiation. This allows flexibility in modifying object creation logic without changing external code.

Code:

Problem Statement:
Implement a factory method for creating products with predefined configurations.

java

class Product {
    private String name;

    // Private constructor to restrict object creation
    private Product(String name) {
        this.name = name;
    }

    // Factory methods
    public static Product createLaptop() {
        return new Product("Laptop");
    }

    public static Product createPhone() {
        return new Product("Phone");
    }

    public String getName() {
        return name;
    }
}

public class Main {
    public static void main(String[] args) {
        // Creating objects using factory methods
        Product laptop = Product.createLaptop();
        Product phone = Product.createPhone();

        System.out.println("Product 1: " + laptop.getName());
        System.out.println("Product 2: " + phone.getName());
    }
}

Output:

Product 1: Laptop
Product 2: Phone

Explanation:
The factory methods (createLaptopcreatePhone) control how objects are created, and external classes cannot directly instantiate the Product class.

4. Preventing Subclassing

A private constructor prevents inheritance by ensuring that no subclass can call the parent class constructor. This is useful for creating immutable classes or enforcing specific behaviors in the class hierarchy.

Code:

Problem Statement:
Create a class that cannot be subclassed to ensure immutability.

java

final class ImmutableClass {
    private ImmutableClass() {
        System.out.println("This class cannot be subclassed");
    }

    public static ImmutableClass createInstance() {
        return new ImmutableClass();
    }
}

// Uncommenting this will cause a compile-time error
// class SubClass extends ImmutableClass {}

public class Main {
    public static void main(String[] args) {
        ImmutableClass obj = ImmutableClass.createInstance();
    }
}

Output:

This class cannot be subclassed

Explanation:
The private constructor ensures that no other class can extend ImmutableClass, preserving its immutability and behavior.

5. Uninstantiable Classes

Classes meant for storing constants or grouping static methods do not need instances. A private constructor prevents unnecessary instantiation, making the class clear in its intent.

Code:

Problem Statement:
Create a class to store application-wide constants without allowing object creation.

java

class AppConstants {
    // Private constructor to prevent instantiation
    private AppConstants() {
        throw new UnsupportedOperationException("Cannot instantiate AppConstants");
    }

    public static final String APP_NAME = "MyApplication";
    public static final int VERSION = 1;
}

public class Main {
    public static void main(String[] args) {
        System.out.println("App Name: " + AppConstants.APP_NAME);
        System.out.println("Version: " + AppConstants.VERSION);
    }
}

Output:

App Name: MyApplication
Version: 1

Explanation:
The private constructor ensures that the class serves its intended purpose of storing constants and cannot be instantiated.

Implementing a Private Constructor in a Singleton Class

Singleton class ensures that only one instance of the class exists throughout the application. This is achieved using a private constructor to prevent external instantiation and a static method to provide controlled access to the instance.

Here’s a step-by-step guide to implementing a Singleton class in Java.

Step 1: Declare a private static instance variable

  • This static variable holds the single instance of the class.
  • Initially, the variable is null.

Step 2: Define a private constructor

  • The constructor is private to restrict instantiation from outside the class.
  • It ensures that no other class can create an object of this class.

Step 3: Implement a public static getInstance method

  • This method checks if the instance is already created. If not, it creates one.
  • Returns the same instance for every subsequent call.

Code Example

Create a Singleton class to manage configuration settings in an application. Ensure that only one instance exists and demonstrate its behavior.

java

// Singleton class implementation
class ConfigManager {
    // Step 1: Static variable to hold the single instance
    private static ConfigManager instance;

    public int value; // Example variable to demonstrate instance sharing

    // Step 2: Private constructor to restrict instantiation
    private ConfigManager() {
        System.out.println("ConfigManager Instance Created");
        value = 0;
    }

    // Step 3: Public static method to provide access to the instance
    public static ConfigManager getInstance() {
        if (instance == null) {
            instance = new ConfigManager();
        }
        return instance;
    }
}

public class Main {
    public static void main(String[] args) {
        // Accessing the Singleton instance
        ConfigManager config1 = ConfigManager.getInstance();
        ConfigManager config2 = ConfigManager.getInstance();

        // Modifying a shared variable using one reference
        config1.value += 42;

        // Verifying that the second reference points to the same instance
        System.out.println("Value from config1: " + config1.value);
        System.out.println("Value from config2: " + config2.value);
    }
}

Output

ConfigManager Instance Created
Value from config1: 42
Value from config2: 42

Explanation

  1. Static Instance Variable:
    The instance variable ensures that only one instance of the ConfigManager class exists.
  2. Private Constructor:
    The private constructor prevents external classes from creating an object using new ConfigManager().
  3. Static Method:
    The getInstance method creates the instance only when it's accessed for the first time. Subsequent calls return the same instance.

Shared State:
Changes made to the value variable using config1 are reflected in config2, proving that both references point to the same instance.

upGrad’s Exclusive Software and Tech Webinar for you –

SAAS Business – What is So Different?

 

Implementing a Private Constructor for Utility Classes 

Utility classes are designed to hold only static methods or constants. These classes are not meant to be instantiated. Using a private constructor ensures no one can create an object of the class, keeping it functional and straightforward.

Why Use Private Constructors in Utility Classes?

  1. Prevents Object Creation: A private constructor blocks anyone from creating an instance of the class.
  2. Clarifies Purpose: Shows that the class is for static methods only.
  3. Reduces Errors: Avoids accidental instantiation and keeps the code clean.

Code Example: StringUtils Class

Create a StringUtils class with static methods to reverse a string and check if a string is a palindrome. Ensure no one can create an object of this class.

Code:

java

// Utility class for text operations
public class StringUtils {

    // Private constructor to block instantiation
    private StringUtils() {
        throw new UnsupportedOperationException("This is a utility class and cannot be instantiated");
    }

    // Static method to reverse a string
    public static String reverse(String input) {
        if (input == null) {
            return null;
        }
        return new StringBuilder(input).reverse().toString();
    }

    // Static method to check if a string is a palindrome
    public static boolean isPalindrome(String input) {
        if (input == null) {
            return false;
        }
        String reversed = reverse(input);
        return input.equalsIgnoreCase(reversed);
    }
}

public class Main {
    public static void main(String[] args) {
        // Using static methods directly
        String text = "Level";

        System.out.println("Original: " + text);
        System.out.println("Reversed: " + StringUtils.reverse(text));
        System.out.println("Is Palindrome: " + StringUtils.isPalindrome(text));

        // Uncommenting this line will cause an exception
        // StringUtils utils = new StringUtils();
    }
}

Output

 

Original: Level
Reversed: leveL
Is Palindrome: true

Explanation

  1. Private Constructor:
    • The constructor is private and throws an exception if someone tries to instantiate the class.
    • This ensures the class is used only as a utility and not for creating objects.
  2. Static Methods:
    • reverse: Reverses the given string using StringBuilder.
    • isPalindrome: Checks if the original string matches its reversed version.
  3. Usage:
    • Call the methods directly using the class name (StringUtils.reverse(text)).
    • No object creation is needed.
  4. Preventing Instantiation:
    • If someone tries to create an object with new StringUtils(), it will throw an exception, making it clear that the class is not for instantiation.

Using Private Constructors in the Builder Pattern

The Builder pattern helps create complex objects step by step. Using a private constructor in the main class ensures that only the Builder class is responsible for creating objects. This approach avoids creating multiple constructors and keeps the code simple and clear.

Why Use Private Constructors in the Builder Pattern?

  1. Control Object Creation:
    A private constructor ensures that the object can only be created through the Builder class.
  2. Flexible Object Creation:
    You can create objects with only the necessary fields without writing multiple constructors.
  3. Improves Readability:
    The Builder pattern separates the object creation process from the class itself, making the code easier to understand.

Code Example: Employee Class with Builder Pattern

Create an Employee class with fields like nameage, and department. Use the Builder pattern to allow flexible object creation.

Code:

java

public class Employee {
    // Fields of the Employee class
    private final String name;
    private final int age;
    private final String department;

    // Step 1: Private constructor to restrict direct instantiation
    private Employee(String name, int age, String department) {
        this.name = name;
        this.age = age;
        this.department = department;
    }

    // Step 2: Inner Builder class to manage object creation
    public static class Builder {
        private String name;
        private int age;
        private String department;

        // Step 3: Setter methods for each field
        public Builder setName(String name) {
            this.name = name;
            return this; // Enable method chaining
        }

        public Builder setAge(int age) {
            this.age = age;
            return this;
        }

        public Builder setDepartment(String department) {
            this.department = department;
            return this;
        }

        // Step 4: Build method to create the Employee object
        public Employee build() {
            return new Employee(name, age, department);
        }
    }

    // Method to display Employee details
    @Override
    public String toString() {
        return "Employee{name='" + name + "', age=" + age + ", department='" + department + "'}";
    }

    // Main method to demonstrate the Builder Pattern
    public static void main(String[] args) {
        // Step 5: Using the Builder class to create an Employee object
        Employee employee = new Employee.Builder()
            .setName("John Doe")
            .setAge(30)
            .setDepartment("Software Development")
            .build();

        System.out.println(employee);

        // Creating another Employee with partial fields
        Employee anotherEmployee = new Employee.Builder()
            .setName("Jane Smith")
            .setDepartment("HR")
            .build();

        System.out.println(anotherEmployee);
    }
}

Output

Employee{name='John Doe', age=30, department='Software Development'}
Employee{name='Jane Smith', age=0, department='HR'}

Explanation

  1. Private Constructor in Employee:
    • The Employee class has a private constructor to restrict direct object creation.
    • Only the Builder class can call this constructor.
  2. Inner Builder Class:
    • This class is nested within the Employee class and is responsible for creating Employee objects.
    • It has fields that match the Employee class and setter methods to set their values.
  3. Setter Methods:
    • Each field has a setter method in the Builder class.
    • The return this; statement allows chaining multiple setter calls.
  4. Build Method:
    • The build() method creates and returns an Employee object using the Builder’s field values.
  5. Flexible Object Creation:
    • The first Employee object is created with all fields.
    • The second Employee object only sets name and department, leaving age to its default value (0).

Why Study Software Development Online? 

Studying software development online is a practical choice today. Online learning offers flexibility, making it easier to balance work, life, and education. As the demand for tech professionals grows, having strong programming skills is more important than ever.

  • Flexible Learning: Learn at your own pace, anytime, anywhere.
  • In-Demand Skills: Software jobs are growing by 22% globally over the next five years.
  • Recognized Certifications: 95% of employers value online certifications like traditional degrees.

With online courses, you can gain valuable skills without disrupting your routine.

Why Choose upGrad?

upGrad’s Software Development courses are designed for learners of all levels. They provide practical knowledge and industry-recognized certifications to help you grow in your career.

  • Expert Guidance: Learn from top industry experts.
  • Real Projects: Build a strong portfolio with hands-on projects.
  • Job-Ready Skills: Master Java, design patterns, and problem-solving.

Start Your Journey with upGrad
Stay ahead in the tech industry with upGrad's online programs.

Learn Software Development Online from Top Universities

Earn an Executive PG ProgramAdvanced Certificate, or Master’s Degree in software development. Gain industry-relevant skills and fast-track your career today!

Enhance your expertise with our Software Development Free Courses. Explore the programs below to find your perfect fit.

Advance your in-demand software development skills with our top programs. Discover the right course for you below.

Frequently Asked Questions (FAQs)

1. Can a constructor be private in Java?

Yes, a constructor can be private in Java. A private constructor restricts object creation from outside the class, allowing instantiation only within the class itself.

2. What is the main purpose of a private constructor?

A private constructor's primary purpose is to control how and when class objects are created. It is commonly used in Singleton patterns, utility classes, and classes following the Factory design pattern.

3. Can we create an object with a private constructor in Java?

Direct object creation from outside the class is not allowed with a private constructor. However, objects can still be created indirectly using methods within the class, such as a static factory method.

4. How do private constructors work in Singleton classes?

Private constructors ensure that only one class instance is created in Singleton classes. A static method or block checks and returns the single instance, preventing additional instances from being created.

5. What are the limitations of using private constructors?

Private constructors prevent external instantiation, which can make testing or subclassing challenging. They also require alternative mechanisms, like factory methods, to provide controlled access to objects.

6. Can a class with a private constructor be subclassed?

No, a class with a private constructor cannot be subclassed. This is because the subclass would require access to the superclass's constructor, which is impossible if the constructor is private.

7. Why are private constructors used in utility classes?

Utility classes often contain only static methods and fields. A private constructor ensures that no objects of the utility class can be created, making it clear that the class is meant only to provide reusable functionalities.

8. How is a private constructor implemented in the Factory pattern?

In the Factory pattern, private constructors restrict the direct instantiation of objects. The factory method within the class creates and returns instances, providing controlled and flexible object creation.

9. What is constructor chaining with private constructors?

Constructor chaining occurs when one constructor calls another. With private constructors, chaining is used internally within the class to reuse initialization logic across multiple constructors.

10. How can I test a class with a private constructor?

To test a class with a private constructor, you can use reflection to bypass access restrictions temporarily. Alternatively, focus on testing the public or static methods that interact with the private constructor.

11. Is it possible to have multiple private constructors in a class?

Yes, a class can have multiple private constructors, each designed for specific initialization requirements. This is particularly useful when the class needs different configurations for internal use.

RELATED PROGRAMS