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!

Yes I think your code will give you exactly one instance of your class.

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

Put an else statement in your getInstance method that reads

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

then try calling getInstance twice. :)

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;
    }
}

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.