File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes constructor private ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "constructor private ?" Watch "constructor private ?" New topic

constructor private ?

samdeep aarzoo
Ranch Hand

Joined: Jun 09, 2005
Posts: 160
can we make constructor private
is it legal to make constructor private
Richard Anderson
Ranch Hand

Joined: May 20, 2005
Posts: 61
Yes, you can make your contructor private; this is typically what you do when implementing the Singleton pattern.


public class MyClass {
private MyClass myInstance = null;

private MyClass() {

public static MyClass getInstance() {
if (myInstance == null) {
myInstance = new MyClass;

return myInstance;

And to use, put the following in your main method:

MyClass myClass = MyClass.getInstance();

Notice that you call getInstance() instead of "new MyClass()", which you wouldn't be able to do without a compiler error.

-Rich, SCJP

-Rich, SCJP 1.4
fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11952

It is also used anytime you don't want anybody to be able to instantiate your class. Utility classes come to mind, like the Math class... all the useful methods are static, so you don't NEED to create an instance.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Ilja Preuss

Joined: Jul 11, 2001
Posts: 14112
Another pattern where it's used is the Typesafe Enum pattern, where the only instances are static final fields inside the class itself.

The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
I agree. Here's the link:
subject: constructor private ?
It's not a secret anymore!