Java Program to Create a Singleton Class

You are currently viewing Java Program to Create a Singleton Class

Java program to create a singleton class

// Java program to create Singleton class

class Singleton {
  private static Singleton singleRef = null;

  private Singleton() {
    System.out.println("Hello from Singleton class");
  }

  public void SayHello() {
    System.out.println("Hello world");
  }

  public static Singleton getSingletonInstance() {
    if (singleRef == null)
      singleRef = new Singleton();

    return singleRef;
  }
}

class Main {
  public static void main(String args[]) {
    Singleton obj = Singleton.getSingletonInstance();

    obj.SayHello();
  }
}

Output

Hello from Singleton class
Hello world

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply