Why do we need a private constructor?

后端 未结 10 563
一整个雨季
一整个雨季 2020-11-30 18:20

If a class has a private constructor then it can\'t be instantiated. So, if I don\'t want my class to be instantiated and still use it, then I can make it static.

Wh

10条回答
  •  佛祖请我去吃肉
    2020-11-30 18:32

    Purpose to create the private constructor within a class

    1. To restrict a class being inherited.

    2. Restrict a class being instantiate or creating multiple instance/object.

    3. To achieve the singleton design pattern.

      public class TestPrivateConstructor
      {
          private TestPrivateConstructor()
          {  }
      
          public static int sum(int a , int b)
          {
              return a + b;
          }
      }
      
      class Program
      {
          static void Main(string[] args)
          {
              // calling the private constructor using class name directly 
              int result = TestPrivateConstructor.sum(10, 15);
              // TestPrivateConstructor objClass = new TestPrivateConstructor(); // Will throw the error. We cann't create object of this class
          }
      }
      

提交回复
热议问题