How to create Singleton class in JAVA?

Java Singleton class interview questions

    Why not use static class over singleton class?

    Below are notable points for using singleton over static

  • a static class is always an inner class.
  • Singleton class can implement interfaces and extend classes. A static class can extends classes but can not inherit its non-static members.
  • A static class can have static members only.
  • Singleton class can be lazily loaded, whereas static class initializes when it is loaded.
  • By using Static class we will not be able to use Object-Oriented features.
  • We can clone the object of Singleton but, we can not clone the static class object.

Singleton class code example

  
  public class Singleton {
	private static volatile Singleton _instance;

	public static Singleton getInstance() {
		//Class level Lock as it is a static instance
		if (_instance == null) {
			synchronized (Singleton.class) {
				if (_instance == null) {
					_instance = new Singleton();
				}
			}
		}
		return _instance;
	}
} 
  
  
Previous
Next Post »

Pages