tauk

Java Singleton Example

Oct 6th, 2021
841
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.88 KB | None | 0 0
  1. //Sun as a Singleton - example
  2. class Sun {
  3.  
  4.     //STEP 2 - make class create instance of itself
  5.     private static Sun instance = new Sun();
  6.  
  7.     private Sun() { //STEP 1 - make all constructors private
  8.     }
  9.  
  10.     public String toString() {
  11.         return "the sun";
  12.     }
  13.  
  14.     //STEP 3 - provide a static getInstance method
  15.     public static Sun getInstance() {
  16.         return instance;
  17.     }
  18. }
  19.  
  20.  
  21. public class SunTester {
  22.     public static void main(String args[]) {
  23.         //create object using static getInstance() method
  24.         Sun sun1 = Sun.getInstance();
  25.         Sun sun2 = Sun.getInstance();
  26.  
  27.         //call instance methods using object ref
  28.         System.out.println(sun1.toString());
  29.  
  30.  
  31.         //if both sun1 and sun2 object refs point to same object
  32.         //this comparison will be true
  33.         System.out.println(sun1 == sun2);
  34.         //and object hashcode will be same also
  35.         System.out.println(sun1.hashCode() + " = " +sun2.hashCode());
  36.  
  37.     }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment