I don't fully understand the concept of Singleton class in Java. For example I have singleton class like this:
private int i = 0;
private static Singleton INSTANCE = new Singleton();
public static Singleton getInstance() {
return INSTANCE;
}
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
So every time I call getInstance() isn't it creating a new Object of Singleton because of this: new Singleton()
?
Then why if I initializes it like this :
Singleton s = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
s.setI(5);
System.out.println(s.getI());
System.out.println(s2.getI());
I'm getting '5' two times. Shouldn't it write 0 to me the second time? I'm truly missing something but no idea what.