Last Updated: 30 September, 2023
A private constructor in Java is a constructor of a class specified with the "private" access modifier. A private constructor can only be accessed from within the class that declared it. This means that the class's objects cannot be created from outside the class.
Private constructors are often used for various design patterns and scenarios to control the instantiation of objects.
Let's see how to define a private constructor in Java:
A private constructor is used in the singleton design pattern, utility classes, and factory methods in Java.
A constructor cannot be abstract, final, synchronized, or static in Java.
A private constructor can be used to prevent subclassing.
A private constructor can be used with static member-only classes.
Let's see the implementation of the private constructor in Java.
In Java, when we specify a private access modifier with the class properties (such as variables, methods, and constructors), that means we cannot access private properties outside the class. This is a restriction with the private access modifiers; if we try access outside the class, we will get a compile time error.
In the below example, there is a class named Test, and it has a private constructor. If we are trying to create the object of the Test class outside the class, then we will get a compile time error. Let's see the example below.
Output
Exception in thread "main" java.lang.Error: Unresolved compilation problem: The constructor Test() is not visible at com.javabytechie.privateconstructor.PrivateConstructorExample.main(PrivateConstructorExample.java:14)
Output
Private Constructor Called...
display() method called...
In the above example, there is a private constructor in the class, creating an object inside the class and calling the display() method of the same class. This is valid, and the output will be generated without error.
Output
Private Constructor Called...
display() method called...
If a class has private constructors, then that class cannot be extended. If we try to extend, we will get a compile-time error. For understanding this scenario, below is an example that is invalid in Java; don't try to implement it.
That's all guys, hope this Java article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com