This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
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

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
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: 11153

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
subject: constructor private ?
Similar Threads
singleton object
final and abstract
A Final class without instantiation
Rules for Constructors - K&B Page 315
constructor private ?