Q:

Java program to compare instances of singleton class

belongs to collection: Java Class and Object Programs

0

Java program to compare instances of 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 compare instances of the singleton class is given below. The given program is compiled and executed successfully.

// Java program to compare instances of Singleton class

class Singleton {
  private static Singleton singleRef = null;

  private Singleton() {}

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

    return singleRef;
  }
}

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

    if (obj1 == obj2 && obj1 == obj3)
      System.out.println("All objects are pointing to the same memory location.");
    else
      System.out.println("All objects are not pointing to the same memory location.");
  }
}

Output:

All objects are pointing to the same memory location.

Explanation:

In the above program, we created a singleton class Singleton and public class Main. The Singleton class contains a method that returns the instance of class.

The Main class contains a static method main(). The main() is an entry point for the program. And, created the instances obj1obj2obj3 and compared all objects, and printed the appropriate message.

 

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 a singleton class with meth... >>
<< Java program to create instances of singleton clas...