Rajendra Jadi
Rajendra Jadi

Reputation: 187

What is the use of private constructor in java?

private constructor do not allow to create objects for example here is code..

class emp
{
    private emp()//private constructor
    {

    }
}

public class privateconstructor
{

    public static void main(String[] args)
    {
        emp e = new emp();//throws Error as constructor not visible

    }

}

By declaring the class as abstract user can also be prevented to create object ..so my question is why private constructor?
Just for Info:
Though object can be created by static method for example..

class emp
{
    private emp()//private constructor
    {

    }
    static emp createInstance()//static method
    {
        return new emp();//returns an instance
    }

    void disp()
    {
        System.out.println("member function called");
    }
}

public class privateconstructor
{

    public static void main(String[] args)
    {
        emp e = emp.createInstance();//creating object by static method  
        e.disp();

    }

}

output: member function called

Upvotes: 0

Views: 686

Answers (2)

Sachin Verma
Sachin Verma

Reputation: 3812

There are some Objects that depend on specific things. Suppose Runtime class , its instance will be dependent on System's current Runtime environment. So instead of,

Runtime run = new Runtime();  //java.lang.Runtime

RunTime's Object is created by:

Runtime ru = Runtime.getRuntime();

So classes that do not let Objects to be created just like that use private constructor.

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533880

so my question is why private constructer?

This is done to prevent construction of a class from any other class. This is usually used in utility classes, singletons, or classes which have factory methods instead of constructors.

All enum classes have private constructors and they can also be useful for Utility and Singleton classes.

Upvotes: 5

Related Questions