I'm studying static in java but while I am playing with codes, my constructor was only called once (no error) even though I am calling it more than twice using a static method that returns static object. Why is that? please help me understand this.
Output: Constructor called
public class Other {
private static Other instance = new Other(); // my constructor is here
private Other() {
System.out.println("Constructor called ");
}
public static Other getInstance() {
return instance; // this will return the static object declared
}
}
public class Main {
public static void main(String[] args) {
// calling static method 4 times that returns static object
Other.getInstance();
Other.getInstance();
Other.getInstance();
Other.getInstance();
}
}