You can have private methods in a public class, because you want to restrict access to those methods. Similarly you can have private constructors to prevent them being used outside the class, even when there are other public methods.
Joined: Feb 07, 2005
Because there are situations where you want the class to be visible, but not allow the user to create more than once instance of the class, like in the singleton pattern.
There are different situations where you might want instance variables, constructors or methods to have certain access control even if the class is public.
You are probably most familiar with a public class with a public constructor. Any time you use new Something() from some other class you are invoking a public constructor.
If the class has a private constructor, then new Something() from another class will not compile. This is useful when you want to control who can create instances of some class. We can use the Singleton Pattern when we want to have exactly one instance of some class. It's often implemented like this:
Does that help?
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Joined: May 31, 2006
so you mean to say if we have a class public but constructor as a private then if that class instance is created more than once then it will give error..right ??
Originally posted by varungoyal goyal: so you mean to say if we have a class public but constructor as a private then if that class instance is created more than once then it will give error..right ??
No. If there's a class with a private constructor, then that class can construct instances of itself, but no other code can. That class can then choose to construct only one instance, and not provide any way for any other class to create any other instances.
For an example, look at the java.lang.Runtime class. You can get an instance by calling the static method Runtime.getRuntime(), but can you construct your own separate instance? Go ahead and try!