Singleton Class in Java

What is Singleton class in java?

Singleton class is a class of which we can create only one object.

Java program to create Singleton class / Implementing a Singleton class :

public class SingltonClassTest {

private static SingltonClassTest t = new SingltonClassTest();

private SingltonClassTest()

{

//don’t allow to create object

}

public static SingltonClassTest getSingltonClassTest() {

// method id static because object is static

return t;

}

 

public static void main(String[] args) {

SingltonClassTest t1 = SingltonClassTest.getSingltonClassTest();

SingltonClassTest t2 = SingltonClassTest.getSingltonClassTest();

SingltonClassTest t3 = SingltonClassTest.getSingltonClassTest();

System.out.println(“Hashcode of t1==” + t1.hashCode());

System.out.println(“Hashcode of t2==” + t2.hashCode());

System.out.println(“Hashcode of t3==” + t3.hashCode());

}

}

Output:
Hashcode of t1==366712642
Hashcode of t2==366712642
Hashcode of t3==366712642

 

Here same hash code is getting printed for all three objects as it is a Singleton class.

Thanks for visiting Ajitation.com, Ajitation is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content.