How to Make Singleton Class In Java

package com.javavogue;

public class SingletonDemo {

static SingletonDemo obj;
private  SingletonDemo(){
}

public static SingletonDemo getInstance(){
if(obj!=null){
return  obj;
}
else{
obj=new SingletonDemo();
return obj;
}
}

public static void main(String[] args) {

SingletonDemo obj1 = SingletonDemo.getInstance();
SingletonDemo obj2 =  SingletonDemo.getInstance();

if( obj1 == obj2 ){
System.out.println(” singleton object “);
}else{
System.out.println(” not singleton object “);
}

System.out.println(obj1==obj2);
}

}

Output:

singleton object
true

One comment

  1. public class SingletonDemo {
    private SingletonDemo() {
    }

    public static SingletonDemo getInstance() {
    return Wrapper.instance;
    }

    private static class Wrapper {
    private static SingletonDemo instance = new SingletonDemo();
    }

Leave a Reply

Your email address will not be published. Required fields are marked *

63 − = 53