Online Tutorials & Training Materials | STechies.com
Register Login

Private Constructor in Java with Example

|| || 0

Private Constructor in Java with Example
Stechies

What is Private Constructor in Java?

Private Constructor is an object created in the class and used internally in the class, means you cannot use this object outside the class, it is a private constructor. Using private constructor we can restrict the use of object outside the class.  

We can initialize the object working within the constructor where we can initialize the object’s state like methods, also contains a collection of instructions that are executed at the time of Object creation.

The private constructor is a mechanism which is defined by java, where definitions are available for constructor regarding access control, functionality and security procedures. In constructor methods are declared private so that it can only access within the class, actually, this privatization restricts the object access outside the class, restricting caller from creating further objects.

public class PvtConstrt{
   private static PvtConstrt abc=null;
   private PvtConstrt(){
      /*it restricts further access of class*/
   }
   public static PvtConstrt abcectCreationMethod(){
	
	if(abc==null){
	    abc= new PvtConstrt();
	}
        return abc;
   }
   public void display(){
	System.out.println("Private Construtctor Example");
   }
   public static void main(String args[]){
	
	PvtConstrt myabcect= PvtConstrt.abcectCreationMethod();
	myabcect.display();
   }
}

Use of Private Constructor

The Use of the private constructor to restrict the object creation outside the class further, Singleton pattern can be implemented using a private constructor can take an example.

Singleton classes use the private constructor, where singleton class restricts the object creation outside the class. We will see in the below example how to use the private constructor for limiting the number of objects for a singleton class.

public class akalton {
   
   private static akalton abc=null;
   private akalton(){
     
   }
   public static akalton abcectCreationMethod(){
	
	if(abc==null){
	    abc= new akalton();
	}
        return abc;
   }
   public void display(){
	System.out.println("Singleton  Example");
   }
   public static void main(String args[]){
	
	akalton myabcect= akalton.abcectCreationMethod();
	myabcect.display();
   }
}

Examples of Private Constructor in Java

 Static function (basically a singleton) to make an uninitializable class which is a collection of related static functions which will work only on the parameter instead of class. Dependencies that are injected often this can be easier to maintain the API when the implementation requires a large number of dependencies.

There are three uses of the private constructor. To restrict instantiation outside of the object in following cases.

  • Singleton
  • Factory method
  • Static method (utility) class
  • Constant only class

## Example Program -1

public class Hell{
   String name;
   //Constructor
   Hell(){
      this.name = "Java books are available";
   }
   public static void main(String[] args) {
      Hell obj = new Hell();
      System.out.println(obj.name);
   }
}

## Example Program -2

public class Cheking {
   private static Cheking instance;
   private Cheking(){}
 
   public static Cheking getInstance(){
      if(instance == null){
         instance = new Cheking();
      }
      return instance;
   }
 
   public static void main(String[] args) {
      Cheking cheking = Cheking.getInstance();
      Cheking cheking1 = Cheking.getInstance();
      System.out.println(cheking.equals(cheking1));
   }  
}

How to call Private Constructor?

A private constructor can be called in many ways either reflections but sometimes this techniques fails the actual meaning of the Purpose. Practical language details should matter far more. Knowing the more general utility of reflection is probably sufficient. 

import java.lang.reflect.Constructor;

public class refl_Example {
    public static void main(final String[] args) throws Exception {
        Constructor<Mnop> constructor = Mnop.class.getDeclaredConstructor();
        constructor.setAccessible(true);
        Mnop Mnop = constructor.newInstance();
        System.out.println(Mnop);
    }
}

class Mnop {
    private Mnop() {
        // private!
    }

    @Override
    public String toString() {
        return "I'm a Tall persone !";
    }
}

 

A static method is the other way to call Private Construction, private constructors cannot be access from the outside the class. This could be used for a class with only static support methods. Accessing a private constructor is by creating a public static method within this class and has its return type as its object.

public class ClassToAccess
{

    public static void main(String[] args)
    {
        {
            ClassWithPrivateConstructor obj = ClassWithPrivateConstructor.getObj();
            obj.printsomething();
        }

    }


Related Articles