What is a singleton class in Java?



A singleton class in Java is the one which can have only one object.

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 −

Example

public class Singleton {
   private static Singleton singleton = new Singleton(); private Singleton() { }
   
   public static Singleton getInstance() {
      return singleton;
   }

   protected static void demoMethod() {
      System.out.println("demoMethod for singleton");
   }
}

Here is the main program file where we will create a singleton object −

public class SingletonDemo {
   public static void main(String[] args) {
      Singleton tmp = Singleton.getInstance();
      tmp.demoMethod();
   }
}
karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know


Advertisements