Q:

Java program to create instances of singleton class and print hash codes

belongs to collection: Java Class and Object Programs

0

Java program to create instances of singleton class and print hash codes

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 instances of singleton class and print hash codes is given below. The given program is compiled and executed successfully.

// Java program to create instances of Singleton class 
// and print Hash codes

class Singleton {
  private static Singleton singleRef = null;

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

  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();

    System.out.println("Obj1 Hashcode: " + obj1.hashCode());
    System.out.println("Obj2 Hashcode: " + obj2.hashCode());
  }
}

Output:

Hello from Singleton class
Obj1 Hashcode: 992136656
Obj2 Hashcode: 992136656

Explanation:

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

The Main class contains a static method main(). The main() is an entry point for the program. And, created the instances obj1obj2 and printed the hash code.

The hash code of all references of the Singleton class is the same because A singleton class is a class that can have only one object at a time.

 

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 compare instances of singleton cla... >>
<< Java program to create a singleton class...