Q:

Java program to create a singleton class

belongs to collection: Java Class and Object Programs

0

Java program to create a singleton class

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to create the singleton class is given below. The given program is compiled and executed successfully.

// 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

Explanation:

In the above program, we created a singleton class Singleton and public class Main. The Singleton class contains constructor and two methods getSingletonInstance()SayHello(). The getSingletonInstance() method returns instance of class. The SayHello() method prints "Hello world" message.

The Main class contains a static method main(). The main() is an entry point for the program. Here, we created the object of the Singleton class and called SayHello() method.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Class and Object Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to create instances of singleton clas... >>
<< Java program to create members with access modifie...