3

Possible Duplicates:
Question about constructors in Java
Can a constructor in Java be private?

Can a constuctor be private in Java? in what kind of situation we use it?

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • You should read this: [Question about constructors in Java](http://stackoverflow.com/questions/4676721/quesiton-about-constructors-in-java). This topic is also discussed here. – Harry Joy May 01 '11 at 13:27

4 Answers4

7

Yes. You would probably use this to implement the factory pattern.

Jack Edmonds
  • 31,931
  • 18
  • 65
  • 77
4

You make it impossible to subclass your class if you make all the constructors private:

public class NoChildren
{
   private static final NoChildren instance = new NoChildren();

   private NoChildren() {}

   public static NoChildren getInstance() { return instance; }
    // Add more and try to subclass it to see.
}
duffymo
  • 305,152
  • 44
  • 369
  • 561
  • 3
    Why was this downvoted? It's perfectly correct, and it goes beyond the mere Singleton pattern. – duffymo May 01 '11 at 13:30
3

Yes, constructors can be private in Java and other languages.. The singleton pattern is well known for using a private constructor.

Other examples from the first linked article:

  • Type-Safe Enumerations
  • Class for constants
  • Factory methods

You can make use of a private constructor when you want to control how an object is instantiated, if at all. For example, in C# you can explicitly define a static class and force the class to only contain static members and constants. You can't do this explicitly in Java but you can use a private constructor to prevent instantiation and then define only static members in the class and have basically a static class.

The class for constants is an example of this but you can also use it in a class that might contain utility functions (basic Math operations for example) and it makes no sense to have an instance since it would contain only constants (like pi and e) and static mathematical methods.

Paul Sasik
  • 79,492
  • 20
  • 149
  • 189
2

A constructor can be private. This is most often used for the Singleton Pattern or if you only want access to an object via static factory method.

Example

Class MyClass {

 private MyClass()
 {
  //private
 }

 public static MyClass newInstance()
 {
  return new MyClass()
 }
} 
leifg
  • 8,668
  • 13
  • 53
  • 79