Singleton Class in Java

The Singleton class allows to create only one object for the given class. In order to make the class as Singleton you need to declare the constructor as private so that you can restrict for creating multiple objects for one class. Use static reference variable to make an object as shareable and define the static method to get instance of an object and instance creation can take place in static block.

Step 1: Create the following class named as Logger.java

package com.javatraineronline;

public class Logger {

	private static Logger logger;
	
	static {
		logger = new Logger();
	}
	
	private Logger() {}
	
	public void printLog() {
		
		System.out.println("Printing the logger activity...");
	}
	
	public static Logger getInstance() {
	
		return logger;
	}
}

Step 2: Test the code by creating and another class name TestSingleton.java

package com.javatraineronline;

public class TestSingleton {

	public static void main(String[] args) {
	
		Logger logger = Logger.getInstance(); // Only one instance will be created
		logger.printLog(); 
	}
}