Java Singleton Pattern

Posted by Spencer on Stack Overflow See other posts from Stack Overflow or by Spencer
Published on 2010-05-14T06:42:03Z Indexed on 2010/05/14 6:44 UTC
Read the original article Hit count: 588

I'm used the Singleton Design Pattern

 public class Singleton {
   private static final Singleton INSTANCE = new Singleton();

   // Private constructor prevents instantiation from other classes
   private Singleton() {}

   public static Singleton getInstance() {
      return INSTANCE;
   }
 }

My question is how do I create an object of class Singleton in another class?

I've tried:

Singleton singleton = new Singleton(); 
// error - constructor is private
Singleton singleton = Singleton.getInstance();
// error - non-static method cannot be referenced from a static context

What is the correct code?

Thanks, Spencer

© Stack Overflow or respective owner

Related posts about java

Related posts about design-patterns