-3
class SomeClass{
    static SomeClass(){
    }
}

Here, although we maybe able to create different names, but shouldn't it refer to the same memory location? Analogous to calling the same person once by his proper name, once his nickname? Would it still be a singleton class?

Uddipta_Deuri
  • 63
  • 1
  • 1
  • 7

2 Answers2

2

You can't have a static constructor as it's job is to initialise a this instance object.

In Scala you can write

object SomeClass {

}

To create something between a singleton and static fields of a class.

The simplest way to define a singleton in Java is to use an enum

enum SomeClass {
    INSTANCE;
}

All references to SomeClass.INSTANCE will be the same instance.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
1

This is the correct way to create and publish a singleton, assuming you don't want to use an implicit singleton (like an enum):

public SomeClass
{
    private static class SingletonHolder
    {
        public static final SomeClass INSTANCE = new SomeClass();
    }

    public static SomeClass getInstance()
    {
        return SingletonHolder.INSTANCE;
    }

    private SomeClass()
    {
    }
}
Sean Bright
  • 118,630
  • 17
  • 138
  • 146