Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean to set something to an INSTANCE rather than create a new object?

Tags:

java

instance

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?

like image 558
MagnusCaligo Avatar asked Dec 14 '25 07:12

MagnusCaligo


2 Answers

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).

like image 106
August Avatar answered Dec 16 '25 21:12

August


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.

like image 39
Bohemian Avatar answered Dec 16 '25 22:12

Bohemian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!