Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Can a constructor in Java is private?

Yes, a constructor can be Private in Java.

Possible Scenarios
a. A Class with all static methods.
Suppose you define an utility class with all static methods, then there is no point of creating an Object to this class. In this scenario, you can create a private constructor, so the object is not created from outside.

ArithmeticUtil.java
package com.smaple.app.utils;

public class ArithmeticUtil {

private ArithmeticUtil(){

}

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

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

}

 b. In Singleton Design Pattern.
Singleton pattern restricts the instantiation of a class to one object. That is you can't create more than one object to this class. This is useful when exactly one object is needed to coordinate actions across the system.

c. To get more control on instantiation of objects
We can use it in Singleton Design pattern, builder design pattern and multiton pattern.

You may like
Miscellaneous
Interview Questions
Programming Questions
map vs flatMap
Convert array of strings to a string
Explicitly invoke the default implementation of a method
Regular Expression: Remove all non-numeric characters from string


This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

Can a constructor in Java is private?

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×