33

I want to know that how private constructor is useful in Java. What are the different ways to use private constructor in Java?

Pang
  • 9,564
  • 146
  • 81
  • 122
New_User
  • 395
  • 1
  • 4
  • 7
  • 3
    When you don't want someone to make an instance of your class (by calling the constructor at least). – chris Jun 27 '13 at 12:12
  • possible duplicate - http://stackoverflow.com/questions/2816123/can-a-constructor-in-java-be-private – mtk Jun 27 '13 at 12:13
  • @R Martinho Fernandes i want answer of this question with respect to C++ also... – New_User Jun 27 '13 at 12:14
  • 1
    Then you need to alter your question. You're only asking for a Java scenario. – Thorsten Dittmar Jun 27 '13 at 12:14
  • @AmrutDange, Well C++ provides an alternative solution with free functions instead of utility classes, so that one's gone. – chris Jun 27 '13 at 12:15
  • possible duplicate of [What is the use of making constructor private in a class?](http://stackoverflow.com/questions/2062560/what-is-the-use-of-making-constructor-private-in-a-class) – Ashish Aggarwal Jun 27 '13 at 12:24

11 Answers11

43

private constructor is off course to restrict instantiation of the class.

Actually a good use of private constructor is in Singleton Pattern. here's an example

public class ClassicSingleton {
   private static ClassicSingleton instance = null;
   private ClassicSingleton() {
      // Exists only to defeat instantiation.
   }
   public static ClassicSingleton getInstance() {
      if(instance == null) {
         instance = new ClassicSingleton();
      }
      return instance;
   }
}

this way you can ensure that only one instance of class is active.

Other uses can be to create a utility class, that only contains static methods.

For, more analysis you can look into other Stack overflow answers

Can a constructor in Java be private?

What is the use of making constructor private in a class?

private constructor

Community
  • 1
  • 1
Bhavik Shah
  • 5,125
  • 3
  • 23
  • 40
9

As other answers mentioned, common uses include the singleton pattern, internal constructor chaining and one more:

Java doesn't support what in C# (for example) is known as a "static class" - in other words, a utility class. A utility class is a helper class that's supposed to contain only static members. (Math and System are such cases in Java.) It doesn't make sense for them to be instantiated in any way.

In C#, making a class static makes it implicitly both final/sealed and abstract. In Java, there is no such keyword and you can't make a class final and abstract. So if you had such a utility class, you'd make it final and give it a private constructor that's never called.

Theodoros Chatzigiannakis
  • 28,773
  • 8
  • 68
  • 104
8

private constructor is used when you want that this class can't be intitalise from outside
Uses

Case 1: When creating sington classs

public class SingletonClass {

    public static SingletonClass singletonClass;

    private SingletonClass() {
    }

    public static SingletonClass getInstance() {
        if(singletonClass == null) {
            singletonClass = new SingletonClass();
        }
        return singletonClass;
    }
}

In this case only intialization is done by getInstance method. No one can create Object of SingletonClass form outside.



Case 2: when you don't want any instance of object like in util classes

public final class Util {

    private Util() {
    }
}

In util class all methods are static so no need of creation of its object so in that case private constructor is used

Ashish Aggarwal
  • 3,018
  • 2
  • 23
  • 46
  • According to http://stackoverflow.com/questions/323022/static-class-vs-class-with-private-constructor-and-all-static-properties-and-me I think with static util class, you do not need to create private contructor. – Nam Vu Nov 17 '15 at 05:11
  • 1
    @ZuzooVn in java you cann't create class as static. The question you mentioned in the comment is based upon C# language – Ashish Aggarwal Nov 18 '15 at 06:34
  • ***"No one can create Object of SingletonClass from outside."*** What if outside do SingletonClass s = SingletonClass.getInstance(); ? I think the benefit in your example is to prevent multiple SingletonClass instances exist. – 林果皞 May 30 '16 at 10:46
6

Some reasons where you may need private constructor:

to prevent instantiation outside of the object, in the following cases:

  1. singleton

  2. factory method

  3. static-methods-only (utility) class

  4. constants-only class

You can also refer this code:

public class MySingletonEx 
{

    private static MySingletoneEx instance = new MySingletonEx("This takes a string");;

    private MySingletonEx(final String myString)
    {
        // This is a private constructor
    }

    public static MySingletonEx getInstance() 
    {
        return instance;
    }
}
Dávid Horváth
  • 4,050
  • 1
  • 20
  • 34
Manish Doshi
  • 1,205
  • 1
  • 9
  • 17
5

The use of a private constructor stops it being created by anything 'outside' the object. This is often used in things like the singleton pattern, where it tries to ensure only one instance of the class exists.

This link also offers some good descriptions...

Jimbo
  • 4,352
  • 3
  • 27
  • 44
2

As an addition to the other answers:

If you want to create a singleton class, you need to hide the constructor, so it can only be called internally.

Thorsten Dittmar
  • 55,956
  • 8
  • 91
  • 139
1

IMHO some usage are

  1. in Singleton
  2. From another constructor ..
stinepike
  • 54,068
  • 14
  • 92
  • 112
1

You may not want users of the class to instantiate it directly but instead use a convenient static method instead, for a very contrived builder example:

public FooBuilder {

    private FooBuilder(FooBar bar) {
        ...
    }

    public static FooBuilder using(FooBar bar) {
        return new FooBuilder(bar);
    }

}

You then use it by invoking the static method:

FooBuilder.using(bar) // further chained methods etc...
Jonathan
  • 20,053
  • 6
  • 63
  • 70
0

When you don't want a particular class to be instantiated ever.

Pang
  • 9,564
  • 146
  • 81
  • 122
Harshal Waghmare
  • 1,944
  • 2
  • 20
  • 21
0

Another use of private constructors is to make sure that only a limited set of instances of a class exists.

For example:

public class Color
{
    public static final Color red = new Color("red");
    public static final Color yellow = new Color("yellow");
    public static final Color blue= new Color("blue");

    private Color(String name) {
        this.name = name;
    }

    .
    .
    .
}

This usage has mostly been supplanted by Java enumerations, however.

Arthur Dent
  • 785
  • 3
  • 7
0

Here are some of the uses of private constructors.

  1. Ability to design a singleton pattern(only one instance of the object is shared among all the objects).

2.To limit the number of instance creation.

3.To prevent subclassing.