This is one of the important and mostly asked question in fresher and experienced interview. Singleton class means a class with only one object. It will have only one object which will be returned always when ever we try to create the object of singleton class. We can create our own singleton class. Interviewer will ask you to write your own singleton class, for that you need to remember following points to create your own singleton class :

a) Declare a static resource ( Object of the singleton class ) .
b) Create that resource in the static initialization block so that will be creating at the class loading time.
c) There must be a static method which return the resource.
d) Most importantly Constructor should be made private. 

Hello.java

class Hello{

   static Hello hello;
   
   private Hello(){}

   static {

     hello = new Hello(); 

   }

   public static Hello getHello(){

        return hello;
   
   }

}


A. java

class A{

  public static void main(String[] args){

     Hello h = Hello.getHello();  // return the object created at class loading.
     Hello h1 = Hello.getHello(); // It will also return the same object. 

  }
}




Hello class is the singleton class in which Hello is created in the static initialization block so that object will be created once which is at the time of class loading and will be returned as many times we try to create an object of Hello class. 

Why Constructor is made private ?

It is because object shouldn't be created directly using new operator.

Explanation :

As the Hello class ( Singleton class ) will be loaded the static initialization block will be executed and hence resource will be created and then whenever we call getHello() method it will always return the object created at the time of class loading. 

6 comments:

  1. nice work on singlton class thanks!

    ReplyDelete
  2. Great info. I love all the posts, I really enjoyed, I would like more information about this, because it is very nice., Thanks for sharing

    define deplorable

    ReplyDelete
  3. great information.
    thank you for posting.
    keep sharing.

    ReplyDelete
  4. It was great experience after reading this. thanks for sharing such good stuff with us.
    Core Java Institute in Delhi

    ReplyDelete

Ads 468x60px

.

Ads

.

Featured Posts

Popular Posts

Like Us On FaceBook

Total Pageviews

Online Members

Live Traffic