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

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.