Write a Program with Singleton Class Example

This article will help you to understand Singleton Class Example.

Purpose of the Singleton class is to restrict object creation to only one object of the given class.

We can create a singleton class by making its constructor as private, so that we can restrict the creation of the object.

We will provide a static method to get instance of the object, as we can handle the object creation inside the class only.

In this example we are creating object by using static block of code.

SingletonClassExample class contains singleton class with private constructor and sample method.

SingletonExampleMainClass class contains main method and we will call sampleMethod() from this class.

Also try to create object of Singleton Class and notice the compile time error.

Java Program of Singleton Class Example

Output

sampleMethod of Singleton called
It's good to share...Share on FacebookTweet about this on TwitterShare on LinkedInPin on PinterestShare on Google+Email this to someone

Leave a Reply

Your email address will not be published. Required fields are marked *