Saturday, 20 September 2014

PRIVATE CONSTRUCTORS IN JAVA

Usage: - How to make a class whose instance cannot be created by any other class but except itself-(Singleton Design Pattern)

We generally know that constructors in java uses public access modifier. But in fact, constructors can use other modifiers like private

Eg:

 package com.sample;

 public class MyClass {

   // a zero-argument constructor

    public MyClass(){}

     ...
     ...


The above MyClass class can be used by other classes by importing it and can get an instance of that class.


What if the constructor uses the a private access modifier like

Eg:

 public class MyClass {

   // a zero-argument constructor

    private MyClass(){}

     ...
     ...

In the above case, no other classes can get an instance of the above classes since it is implementing a private constructor.


Let's see one more example:

public class ClientService {

    private static ClientService clientService = new ClientService();

  //private constructor 

    private ClientService() {}

    public static ClientService createInstance() {

        return clientService;
    }


}

The above example uses a private constructor, where its object is created within itself and used, this scenario restrict others to get an instance.


Private constructors are mainly used in Singleton Design Pattern, where a class can be instantiated only once. In such cases, we can use private constructors.

No comments:

Post a Comment