开发者

constructors in java [duplicate]

开发者 https://www.devze.com 2023-01-09 04:00 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicates: Why do we need a private constructor?
This question already has answers here: Closed 12 years ago.

Possible Duplicates:

Why do we need a private constructor?

Can a constructor in Java be private?

whts the use of private constructor in 开发者_开发问答java?


One more thing you can achive is SingleTon pattern with the help of the private constructor.

Some thing like this:

public class ClassicSingleton {
   private static ClassicSingleton instance = null;
   private ClassicSingleton() {
      // Exists only to defeat instantiation.
   }
   public static ClassicSingleton getInstance() {
      if(instance == null) {
         instance = new ClassicSingleton();
      }
      return instance;
   }
}


A private constructor allows the developer of a class to better control how this class can be instantiated, e.g. not at all (for a utility class), only internally (for a singleton) or only through factory methods.

0

精彩评论

暂无评论...
验证码 换一张
取 消