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.
nice work on singlton class thanks!
ReplyDeleteThanks man...!!
DeleteGreat info. I love all the posts, I really enjoyed, I would like more information about this, because it is very nice., Thanks for sharing
ReplyDeletedefine deplorable
great information.
ReplyDeletethank you for posting.
keep sharing.
It was great experience after reading this. thanks for sharing such good stuff with us.
ReplyDeleteCore Java Institute in Delhi
Thanks for sharing the information..... keep sharing more articles
ReplyDeleteWe provide best Selenium training in Bangalore, automation testing with live projects. Cucumber, Java Selenium and Selenium Automation Training in Bangalore
Selenium Training Institutes in Bangalore
Selenium Training in Marathahalli
Best Selenium Automation Training in Bangalore
Selenium Training in Marathahalli
Best Selenium Training in Bangalore
Selenium Software Training in Bangalore
Selenium Training Institutes in Bangalore
Top 10 selenium training institutes in bangalore