fork download
  1. /**
  2.  * Testing singleton creation and clean instance
  3.  *
  4.  */
  5. import java.util.*;
  6. import java.lang.*;
  7. import java.io.*;
  8.  
  9. /* Name of the class has to be "Main" only if the class is public. */
  10. class Ideone
  11. {
  12. public static void main (String[] args) throws java.lang.Exception
  13. {
  14. ASingletonClass a = ASingletonClass.getInstance();
  15. System.out.println("Instance reference of a: "+a);
  16. ASingletonClass b = ASingletonClass.getInstance();
  17. System.out.println("Instance reference of b: "+b+" which is equal to a");
  18. b.clear();
  19. System.out.println("Instances are still same");
  20. System.out.println("Instance reference of a: "+a);
  21. System.out.println("Instance reference of b: "+b+" which is equal to a");
  22.  
  23. System.out.println("After getting instances again, the references changed:");
  24. a = ASingletonClass.getInstance();
  25. System.out.println("Instance reference of a: "+a);
  26. b = ASingletonClass.getInstance();
  27. System.out.println("Instance reference of b: "+b+" which is equal to a");
  28.  
  29. }
  30. }
  31.  
  32. class ASingletonClass
  33. {
  34. private static ASingletonClass instance = null;
  35.  
  36. private ASingletonClass() {}
  37.  
  38. public static ASingletonClass getInstance()
  39. {
  40. if (instance == null)
  41. instance = new ASingletonClass();
  42. return instance;
  43. }
  44. public static void clear()
  45. {
  46. instance = null;
  47. }
  48. }
Success #stdin #stdout 0.11s 36192KB
stdin
Standard input is empty
stdout
Instance reference of a: ASingletonClass@816f27d
Instance reference of b: ASingletonClass@816f27d which is equal to a
Instances are still same
Instance reference of a: ASingletonClass@816f27d
Instance reference of b: ASingletonClass@816f27d which is equal to a
After getting instances again, the references changed:
Instance reference of a: ASingletonClass@7229724f
Instance reference of b: ASingletonClass@7229724f which is equal to a