public class SomeClass {
private static final SomeClass INSTANCE = new SomeClass();
private SomeClass() {}
public static SomeClass getInstance() {return INSTANCE;}
public static void main(String[] args) {
System.out.println(getInstance());
}
}
Why does the getInstance method always return the same reference every time?
The reason is that the field INSTANCE is both static and final.
static means its scope is bound to the enclosing class, and not any single instance of that class. (Even though you're not creating any instances of it anyway.) In a running Java program, there's only one of each class, even though a class may have many instances.
final means that the value of this field cannot be changed after it's initialised.
Because it's static, there's only one "slot" for the object, and because it's final the contents of this slot will never change, which is why returning those contents will always return the same thing.
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