top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to create Singleton Class in Java?

–1 vote
422 views
How to create Singleton Class in Java?
posted Feb 22, 2018 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote
class Singleton
{

    private static Singleton single_instance = null;

    public String s;

    // private constructor restricted to this class itself
    private Singleton()
    {
        s = "I am a string part of Singleton ";
    }

    // static method to create instance of Singleton class
    public static Singleton getInstance()
    {
        if (single_instance == null)
            single_instance = new Singleton();

        return single_instance;
    }
}

// Driver Class

class Main
{
    public static void main(String args[])
    {
        // instantiating Singleton class with variable x
        Singleton x = Singleton.getInstance();

        // instantiating Singleton class with variable y
        Singleton y = Singleton.getInstance();



        // changing variable of instance x
        x.s = (x.s).toUpperCase();

        System.out.println("String from x is " + x.s);
        System.out.println("String from y is" +y.s);

        System.out.println("String from x is " + x.s);
        System.out.println("String from y is " + y.s);

    }
}
answer Mar 6, 2018 by Zohair Assri
...