java Singleton class

Create a Singleton class in java :

In java, when you will create a singleton class, you can’t create more than one instance that is only single instance will be created.

Example :


package com.pkjavacode.com;

public class SingletonDemo {

private static SingletonDemo singleinstance = new SingletonDemo();

private SingletonDemo() {

}

private static SingletonDemo getInstance() {

if (singleinstance == null) {
singleinstance = new SingletonDemo();

System.out.println("AccountCreation Class Object creatred...!!!");
} else {
System.out
.println("AccountCreation Class Object not Creatred just returned
Created one...!!!");
}
return singleinstance;
}

public void create(int no) {
System.out.println("Account Created Successfully, with Number:" + no);
}

public static void main(String[] args) {

SingletonDemo sd = SingletonDemo.getInstance();
SingletonDemo sd2 = SingletonDemo.getInstance();
sd.create(10);
sd2.create(20);
}
}

Output :

AccountCreation Class Object not Creatred just returned Created one…!!!
AccountCreation Class Object not Creatred just returned Created one…!!!
Account Created Successfully, with Number:10
Account Created Successfully, with Number:20