2

I have a Singleton class like this:

class Singleton {
    static class SingletonHolder {
        static final Singleton INSTANCE = new Singleton();
    }
    public static Singleton getInstance() {
        return SingletonHolder.INSTANCE;
    }
}

Can I call like this from other class:

Singleton dummy = new Singleton();

if yes how can I disable it? if not, then why cannot i?

2 Answers 2

7

Sure. Just make the constructor private to avoid that: just add private Singleton() {} to prevent the default constructor from being public.

Sign up to request clarification or add additional context in comments.

Comments

3

I suggest you make it an enum (since they can't be instantiated anyway);

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

1 Comment

well I'm against using enum for singleton. but it has been discussed too many times:)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.