34

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

6
  • 3
    When you don't want someone to make an instance of your class (by calling the constructor at least). Commented Jun 27, 2013 at 12:12
  • possible duplicate - stackoverflow.com/questions/2816123/… Commented Jun 27, 2013 at 12:13
  • @R Martinho Fernandes i want answer of this question with respect to C++ also... Commented Jun 27, 2013 at 12:14
  • 1
    Then you need to alter your question. You're only asking for a Java scenario. Commented Jun 27, 2013 at 12:14
  • @AmrutDange, Well C++ provides an alternative solution with free functions instead of utility classes, so that one's gone. Commented Jun 27, 2013 at 12:15

11 Answers 11

44

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

Sign up to request clarification or add additional context in comments.

Comments

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.

4 Comments

BTW The new approach to static class is enum.
@MarkoTopolnik Can you give an example?
public enum Utility {; public static void fn1() {} }
@MarkoTopolnik Wow. Haven't seen that before. Definitely interesting.
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

3 Comments

According to stackoverflow.com/questions/323022/… I think with static util class, you do not need to create private contructor.
@ZuzooVn in java you cann't create class as static. The question you mentioned in the comment is based upon C# language
"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.
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;
    }
}

Comments

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...

Comments

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.

1 Comment

Yes, see the other 50 answers telling you the same thing :-D
1

IMHO some usage are

  1. in Singleton
  2. From another constructor ..

Comments

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...

Comments

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.

Comments

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.