Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this method call return the same reference every time it’s called?

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?

like image 916
Danny Avatar asked Nov 18 '25 13:11

Danny


1 Answers

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.

like image 82
millimoose Avatar answered Nov 21 '25 01:11

millimoose



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!