Singleton class in Java

Singleton is a class wherein we can create just a single object of that class. Runtime is one of the most important built-in Singleton class in Java library. But we can also create our custom singleton class as shown in below example. Note that we can create only one instance of that class.

package singleton;

import org.junit.Test;

/**
 * Created by ssalunke on 13/04/2016.
 */
public class TestSingleTon {

    @Test
    public void test(){
        System.out.println(SingleTon.getInstance().hashCode());

        //Below statement will throw compile time error
        //Runtime r = new Runtime();

        //Below statement will throw compile time error
        //SingleTon s1 = new SingleTon();

    }
}
class SingleTon {

    private static SingleTon instance = null;

    private SingleTon() {
            // This constructor is private which means that
            //we can not create objects using new Operator
    }

    public static SingleTon getInstance() {
        if (instance == null) {
            instance = new SingleTon();
        }
        return instance;
    }
}

You may also like...