Reputation: 75
I recently learned a Designed pattern called singleton class. before I learned java, i know about keywords like static block (it execute before main method) static keyword(we do not need to create object for calling methods) , final ( we need to specify value / classes cannot be extended/ method cannot be overrided etc) and constructor ( method having same name, which automatically invoke when we create object) etc etc. So here what happen to me is that I am not able to relate everything. please explain me to the dept how this is working and all.? why we used private constructor, static block etc etc. Here it the code, please explain me line by line.
public class Sample {
final static Sample s;
static {
s= new Sample();
}
private Sample() {
}
static Sample getSample() {
return s;
}
}
public class Runner {
public static void main(String[] args) {
Sample s1 = Sample.getSample();
int x=s1.hashCode();
Sample s2 =Sample.getSample();
int y= s2.hashCode();
System.out.println(x);
System.out.println(y);
}
}
Upvotes: 0
Views: 1933
Reputation: 1
A singleton is a design pattern used to ensure there is only one instance of an object created from that class running in an application.
So making the constructor private ensures no one outside that class can create an instance of that object(class).
So static block is used for static initialization of the class and runs only once, so when the main which is in another class runs and Sample s1 = Sample.getSample();
happens, static method runs creating an instance of object Sample as s. Then getSample() sets s1 to that initialized object. So viewing the hashCode of s1 returns the hashcode of the instance of s.
Doing the same to s2 will return the same hashCode as they both came from the same instance s.
Upvotes: 0
Reputation: 563
If you don't define a constructor, then when you do "new SomeClass()", Java will call the default constructor, which is:
public SomeClass() { }
Now, you are applying the Singleton pattern, so you don't want to allow object instantiations from outside the class, that is why you "re-declare" the default constructor but as "private". That way, you can only create an object of this class from the inside. As you can see here:
static {
s = new Sample();
}
I hope this explanation clarifies your doubts.
PS: You can also refer to this article that explains very well the pattern: https://www.journaldev.com/1377/java-singleton-design-pattern-best-practices-examples
Cheers!
Upvotes: 1