What happens if a constructor is declared private in a class

date:2024-06-05 12:29:03 author:admin browse: View comments Add Collection

What happens if a constructor is declared private in a class

What happens if a constructor is declared private in a class?

When a constructor is declared private in a class, it restricts the instantiation of that class. This means objects cannot be created directly from outside the class. However, this doesn’t mean the class can’t be used at all. It’s often employed in design patterns like Singleton and Factory Method where control over object creation is required.

In Singleton pattern, a single instance of the class exists throughout the application. The private constructor ensures only one instance by preventing external instantiation and subclassing.

In Factory Method pattern, the private constructor prevents direct class instantiation, allowing the factory method to handle object creation based on conditions or logic.

Private constructors also prevent subclassing as the child class calls parent’s no-arg constructor implicitly. If it’s private, this call fails leading to compile-time error.

支付宝转账赞助

支付宝扫一扫赞助

微信转账赞助

微信扫一扫赞助