In this example we will show how to use static inner class to develop singleton class in Java.
Source Code
package com.beginner.examples;
public class StaticInnerSingletonExample {
public static void main(String[] args){
// get singleton instance
Singleton s = Singleton.getInstance();
s.test();
}
}
class Singleton {
private Singleton() {}
private static class SingletonInstance {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonInstance.INSTANCE;
}
public void test(){
System.out.println("It is a singleton example.");
}
}
Output:
It is a singleton example.