• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

constructor private ?

 
Ranch Hand
Posts: 160
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
can we make constructor private
is it legal to make constructor private
 
Ranch Hand
Posts: 61
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
lowercase baba
Posts: 13089
67
Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
reply
    Bookmark Topic Watch Topic
  • New Topic