When private keyword is assigned to a method, then that method cannot be access by other outside class, this way we can add security to those methods. Since Constructors are also like methods in Java there comes the question can we assign private keyword to the constructor ? If yes then why?
Why we use Private Constructors ?
When we make the Constructor as private then object for the class can only be created internally within the class, no outside class can create object for this class. Using this we can restrict the caller from creating objects. When we still try to create object we be will getting the error message ” The constructor SingletonExample() is not visible “
package com.javainterviewpoint; class SingletonExample { /** * Private Constructor for preventing object creation from outside class **/ private SingletonExample(){ } public void disp() { System.out.println("disp() method called"); } } public class OutsideClass { public static void main(String args[]) { //Creating the object for the SingletonExample class SingletonExample ss = new SingletonExample(); ss.disp(); } }
When we run the above code we will be getting the below exception.
Exception in thread "main" java.lang.Error: Unresolved compilation problem: The constructor SingletonExample() is not visible at com.javainterviewpoint.OutsideClass.main(OutsideClass.java:17)
In Singleton Design Pattern we will be using this mechanism to prevent other creating object. In this pattern we will be creating the object inside the class and will be providing a public static method which can be called directly to get the object which is created. Lets see the below example how private constructor is used in Singleton Pattern.
package com.javainterviewpoint; class SingletonExample { private static SingletonExample singletonExampleObj = null; /** * Private Constructor for preventing object creation from outside class **/ private SingletonExample(){ } public static SingletonExample getSingletonExampleObject() { /* * *Create object only when "singletonExampleObj" is null and * only one object can be created */ if(singletonExampleObj == null) { singletonExampleObj = new SingletonExample(); } return singletonExampleObj; } public void disp() { System.out.println("disp() method called"); } } public class OutsideClass { public static void main(String args[]) { //Obtaining the object via our public method SingletonExample ss = SingletonExample.getSingletonExampleObject(); ss.disp(); } }
Output :
disp() method called
Leave a Reply