Home » Java programming language

How to make Singleton Class using static in Java?



In this java program, we are going to create singleton class using static block. We will learn this by using simple example and explanation. Submitted by IncludeHelp, on December 14, 2017

What is Singleton Class In java?

A class is said to be a Singleton class when it contains only one object at a time. In singleton class, we use getInstance () method instead of the constructor.

Program to make singleton class in java

// This program will create singleton class using static

public class SingletonClassUsingStatic 
{		 
	public static void main(String args[])
	{
		// create object of class.
		MySingleton ms = MySingleton.getInstance();
		ms.testSingleton();
	}
}

// create singleton class and make private constructor.
class MySingleton
{     
	private static MySingleton instance;

	static
	{
		instance = new MySingleton();
	}

	private MySingleton()
	{
		System.out.println("This is Singleton Object..");
	}

	public static MySingleton getInstance()
	{
		return instance;
	}

	public void testSingleton()
	{
		System.out.println("Class Created..");
	}
}

Output

This is Singleton Object..
Class Created..





Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.



Comments and Discussions


We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.