Create a Singleton Object : Access Control « Class « Java






Create a Singleton Object

 

class MySingleton {
  // the static singleton object
  private static MySingleton theObject;

  private MySingleton() {
  }

  public static MySingleton createMySingleton() {

    if (theObject == null)
      theObject = new MySingleton();

    return theObject;
  }
}

public class Main {
  public static void main(String[] args) {
    MySingleton ms1 = MySingleton.createMySingleton();

    MySingleton ms2 = MySingleton.createMySingleton();

    System.out.println(ms1 == ms2);
  }
}

   
  








Related examples in the same category

1.Visibility
2.Composition with public objects
3.The protected keywordThe protected keyword