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..


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.