mardi 27 octobre 2015

Why singletons static method getNext() returns incremented value

I have a singleton class with a static method getNext()

public class Sequence {

   private static Sequence  instance;
   private static int counter;

   private Sequence () { // note: private constructor
      counter = 0;
   }

   public static Sequence getInstance(){
      if(instance==null) { // Lazy instantiation
         instance = new Sequence(); 
      }
      return instance;
   }

   public static int getNext(){ return ++counter;}
}

In my test code I have a for loop which calls getNext() several times

public class TestSequence {
   public static void main(String[] args) {
      for (int i = 0; i < 5; i++)
         System.out.println(Sequence.getNext());        
   }

}

and output of it is

1
2
3
4
5

Why is that? With my understanding of static I thought that output always will be 1.

I understand use of static method that there is no need to create instance of the class (object). When object is not created, then every call to static getNext() method should increment new (virtual) instance variable counter = 0 and return it.

But my program behave exactly the same way as for non static method. Why? Probably I misunderstand something or simplify things.

Aucun commentaire:

Enregistrer un commentaire