Why should we make the constructor private in class? As we always need the constructor to be public.
相关问题
- how to define constructor for Python's new Nam
- Keeping track of variable instances
- Object.create() bug?
- std::vector of objects / pointers / smart pointers
- Name for a method that has only side effects
相关文章
- 接口B继承接口A,但是又不添加新的方法。这样有什么意义吗?
- NameError: name 'self' is not defined, eve
- Implementation Strategies for Object Orientation
- Check if the Type of an Object is inherited from a
- When to use Interfaces in PHP
- Are default parameters bad practice in OOP?
- How to return new instance of subclass while initi
- In OOP, what is the best practice in regards to us
Sometimes is useful if you want to control how and when (and how many) instances of an object are created.
Among others, used in patterns:
Constructor is private for some purpose like when you need to implement singleton or limit the number of object of a class. For instance in singleton implementation we have to make the constructor private
Again if you want to limit the object creation upto 10 then use the following
Thanks
when you do not want users to create instances of this class or create class that inherits this class, like the
java.lang.math
, all the function in this package isstatic
, all the functions can be called without creating an instance ofmath
, so the constructor is announce as static.One of the important use is in SingleTon class
Its also suitable, If your class has only static methods. i.e nobody needs to instantiate your class
This ensures that you (the class with private constructor) control how the contructor is called.
An example : A static factory method on the class could return objects as the factory method choses to allocate them (like a singleton factory for example).