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() { }
}
Yes, This is the concept of the Singleton design pattern!
This is one way to create a singleton of a class.
So to answer your question:
getStatTest()
method will return that instance.When using this method for a singleton, the method is mostly called getInstance()
=)
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