• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

i have a private constructor and a public constructor

 
slagy maggie
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I have a class, which has one private constructor
public class test extends test1
{
private test{
super();
}
and then a public test(int i, String s){blah blah}
now if i wanted a singleton model, and did not want 2 instances of thsi class, why have a public constructor(that will allow other classes to create other instances ???/!!!11)
and moreover that super(), in the private constructor accesses
the public constructor in test1 class. what all this lead to???does it all not lead to totally counteracting the need a for a private constructor???
thanks guys
 
Doug Gschwind
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually, the singleton model does NOT expose a public constructor. An example is the following:
public class Singleton
{
private static Singleton instance;
private Singleton()
{
super();
}
public static synchronized Singleton getInstance()
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
// other stuff below
}
The call to super() from the private constructor exposes nothing additional to Singleton's consumers. The code above also limits construction to just one instance. Consumers of this class only obtain access to the one instance via the getInstance() class method.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic