0

hey
i have that singleton code in java but how can i check that it have an instance only?

class singleton
{
    private static singleton instance;
    
    private singleton()
    {
    }
    
    public static singleton getInstance()
    {
        if (instance == null){
            instance = new singleton();
        }
        return instance;
    }
}

thanks in advance!

2
Contributors
5
Replies
6
Views
9 Years
Discussion Span
Last Post by darkagn
0

yeah but how can i check that indeed have only one instance?

0

Put an else statement in your getInstance method that reads

System.out.println("Hey, I'm already created!!");

then try calling getInstance twice. :)

0

what do you mean calling the getInstance method twice ???

class singleton
{
    private static singleton instance;
    
    private singleton()
    {
    }
    
    public static singleton getInstance()
    {
        if (instance == null){
            instance = new singleton();
        }else{
            System.out.println("already created");
        }
        return instance;
    }
}
0

You will need to call singleton.getInstance() somewhere in your main method to get the instance of the class. Call it twice to see if you can only create one instance.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.