What is private constructor ,Factory method and Singleton class in JAVA ?

private constructor ,Factory method and Singleton class

Factory Method:-

If the return type of method is class name then it is known as the Factory method. Private constructor defining a “virtual” constructor.

Private Constructor:-

The factory constructor declared with private-keyword is known as private-constructor. If the constructor is private we cannot create an object outside class. The private constructor is used to serve singleton classes.

There are various uses where we can private constructor. The major ones are

1)Internal constructor chaining

2)Singleton class pattern

Singleton class:-

If the class is able to instantiated only for a single time is known as singleton class. Singleton class provides a way to access its only object which can be accessed directly without the need to instantiate(cannot create object) the object of the class.

 

PROGRAM:-

class Test
{
int x=100;
private static int count=0;
static Test obj=null;
private Test() //private ctor
{
System.out.println("private constructor");
}
public static Test getObject() //factory method 
{
if (count<2) //singleton 
{
obj=new Test();
count++;
}
return obj;
}
}
class Demo
{
public static void main(String[] args) 
{
//Test t1=new Test(); Test() has private access in Test
Test t1=Test.getObject();
Test t2=Test.getObject();
Test t3=Test.getObject();

System.out.println(t1);
System.out.println(t2);
System.out.println(t3);
System.out.println(t1.x); 
}
}

O/P:-
private constructor
private constructor
Test@15db9742   
Test@6d06d69c
Test@6d06d69c
100
private
basicittopic

basicittopic

A Computer Science Study for IT students and people of IT community

Leave a Reply