File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
Author

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.

Example:

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
Bartender

Joined: Oct 02, 2003
Posts: 11229
    
  16

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
author
Sheriff

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
 
Don't get me started about those stupid light bulbs.
 
subject: constructor private ?