What is a singleton class in Java?

Java 8Object Oriented ProgrammingProgramming

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();
   }
}
raja
Published on 06-Feb-2018 00:56:14
Advertisements