Can a constructor be private in Java [duplicate]
Possible Duplicates:
Question about constructors in Java Can a constructor in Java be private?
Can a constuctor be private in Java? in what kind of situation we use it?
Yes. You would probably use this to implement the factory pattern.
You make it impossible to subclass your class if you make all the constructors private:
public class NoChildren
{
private static final NoChildren instance = new NoChildren();
private NoChildren() {}
public static NoChildren getInstance() { return instance; }
// Add more and try to subclass it to see.
}
Yes, constructors can be private in Java and other languages.. The singleton pattern is well known for using a private constructor.
Other examples from the first linked article:
- Type-Safe Enumerations
- Class for constants
- Factory methods
You can make use of a private constructor when you want to control how an object is instantiated, if at all. For example, in C# you can explicitly define a static class and force the class to only contain static members and constants. You can't do this explicitly in Java but you can use a private constructor to prevent instantiation and then define only static members in the class and have basically a static class.
The class for constants is an example of this but you can also use it in a class that might contain utility functions (basic Math operations for example) and it makes no sense to have an instance since it would contain only constants (like pi and e) and static mathematical methods.
A constructor can be private. This is most often used for the Singleton Pattern or if you only want access to an object via static factory method.
Example
Class MyClass {
private MyClass()
{
//private
}
public static MyClass newInstance()
{
return new MyClass()
}
}
精彩评论