Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static instance variable references instance of the class

Tags:

java

reference

Can I let a static field of a class keep a reference to an instance of itself? If so, will it keep alive in the jvm without anyone else keeping a reference?

public class StatTest {
    private static StatTest statTest;

    public static StatTest getStatTest () {
        if (statTest== null) {
            statTest= new StatTest ();
            statTest.init();
        }
        return statTest;
    }

    private StatTest() { }
}
like image 653
joaerl Avatar asked Dec 28 '22 11:12

joaerl


2 Answers

Yes, This is the concept of the Singleton design pattern!

like image 56
Abimaran Kugathasan Avatar answered Jan 17 '23 17:01

Abimaran Kugathasan


This is one way to create a singleton of a class.

So to answer your question:

  • Yes, it is possible
  • All references to the getStatTest() method will return that instance.

When using this method for a singleton, the method is mostly called getInstance() =)

like image 31
KristofMols Avatar answered Jan 17 '23 17:01

KristofMols