Where and how can I create a private constructor in Java?

Java 8Object Oriented ProgrammingProgramming

We can use a private contractor in a Java while creating a singleton class. The Singleton's purpose is to control object creation, limiting the number of objects to only one. Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields. Singletons often control access to resources, such as database connections or sockets.


The easiest implementation consists of a private constructor and a field to hold its result, and a static accessor method with a name like getInstance().

The private field can be assigned from within a static initializer block or, more simply, using an initializer. The getInstance( ) method (which must be public) then simply returns this instance –

public class SingletonSample {
   private static SingletonSample singleton = new SingletonSample();
   private SingletonSample() { }

   public static SingletonSample getInstance() {
      return singleton;

   protected static void demoMethod( ) {
      System.out.println("demoMethod for singleton");
   public static void main(String[] args) {
      SingletonSample tmp = SingletonSample.getInstance( );
      tmp.demoMethod( );


demoMethod for singleton
Published on 08-Feb-2018 13:51:38