Alex Rivera | Logout

Can a constructor in Java be private?

Asked 2010-05-12T04:26:29.793
253

Can a constructor be private? How is a private constructor useful?

Edit
Report

3 Answers

113

I expected that someone would've mentioned this (the 2nd point), but.. there are three uses of private constructors:

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

    • singleton
    • factory method
    • static-methods-only (utility) class
    • constants-only class
      .
  • to prevent sublcassing (extending). If you make only a private constructor, no class can extend your class, because it can't call the super() constructor. This is some kind of a synonym for final

  • overloaded constructors - as a result of overloading methods and constructors, some may be private and some public. Especially in case when there is a non-public class that you use in your constructors, you may create a public constructor that creates an instance of that class and then passes it to a private constructor.

answered 2010-05-12T05:04:46.223
27

Yes it can. A private constructor would exist to prevent the class from being instantiated, or because construction happens only internally, e.g. a Factory pattern. See here for more information.

answered 2010-05-12T04:29:48.803
10

Well, if all of your methods in a class are static, then a private constructor is a good idea.

answered 2012-06-28T11:31:18.420

Your Answer