Java program to create a private constructor
class Test {
// create private constructor
private Test () {
System.out.println("This is a private constructor.");
}
// create a public static method
public static void instanceMethod() {
// create an instance of Test class
Test obj = new Test();
}
}
class Main {
public static void main(String[] args) {
// call the instanceMethod()
Test.instanceMethod();
}
}
Output
This is a private constructor.
In the above example, we have created a private constructor of the Test class. Hence, we cannot create an object of the Test class outside of the class.
This is why we have created a public static method named instanceMethod() inside the class that is used to create an object of the Test class. And from the Main class, we call the method using the class name.
Leave a Reply