I was reading some code somewhere on the internet, and I saw this interesting piece that intrigued me and I'm curious how it works.
There is a class called ResourceManager and looks like this:
public class ResourceManager {
private static final ResourceManager INSTANCE = new ResourceManager();
public static ResourceManager getInstance() {
return INSTANCE;
}
}
(It has a bunch of other stuff in it but I don't think its necessary to include). However, what I find interesting is that in the author did not include a constructor. In fact, in his main method he only makes one reference to this class and instead of creating a new object he just writes:
ResourceManager.getInstance().etc();
I have never seen coding like this before. I had to modify it because I needed a ResourceManager object to work with, so what I did was:
ResourceManager res = ResourceManager.getInstance();
Which worked perfectly fine. However, I still don't entirely understand what is going on here. How is this class being created without a constructor?
This is the singleton pattern, meaning that there will only ever be one instance of the class ResourceManager (the constructor should really be private to enforce this).
However, I still don't entirely understand what is going on here. How is this class being created without a constructor?
If you don't explicitly write a constructor, Java will automatically insert a default constructor (assuming the superclass also has a default constructor).
To answer the question about no constructor:
All java classes that have no constructor defined, have an implicit public no-args constructor.
However, there should be a private no-args constructor defined, because this class is clearly intended to be a singleton. But without a private constructor, a new instance can be created at any time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With