In this tutorial, we will learn about how to implement private constructors in Java. In Java, you can create private constructors for a class, which can be used to restrict the instantiation of the class from outside of the class.
A private constructor is a constructor which can only be accessed within the class and cannot be accessed from outside of the class.
Here is an example of a class with a private constructor.
class MyClass { private int x; private MyClass() { this.x = 0; } public void setX(int x) { this.x = x; } public int getX() { return x; } }
In this example, the MyClass class has a private constructor which is only accessible within the class. This means that the class cannot be instantiated from outside the class.
Here is an example of how you can use this class.
// This will cause a compile error MyClass obj = new MyClass();
You will get a compile error if you try to create an object of the class, because the constructor is private and can only be accessed within the class.
To create an object of this class, you can create a factory method within the class to return an instance of the class. For example
class MyClass { private int x; private static MyClass instance; private MyClass() { this.x = 0; } public static MyClass getInstance() { if(instance == null) { instance = new MyClass(); } return instance; } public void setX(int x) { this.x = x; } public int getX() { return x; } }
Now, you can create an object of this class using the factory method.
MyClass obj = MyClass.getInstance();
This way you can control the instantiation of the class and also make sure that only one instance of the class exist in the system. This technique is known as Singleton pattern, which is a design pattern that ensures a class has only one instance, while providing a global access point to this instance.