Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

constructor private ?

 
samdeep aarzoo
Ranch Hand
Posts: 160
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
can we make constructor private
is it legal to make constructor private
 
Richard Anderson
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
fred rosenberger
lowercase baba
Bartender
Posts: 12086
29
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another pattern where it's used is the Typesafe Enum pattern, where the only instances are static final fields inside the class itself.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic