Trying to understand statics is java, Why is it that this is the output in this code?

class Cup {
  Cup(int marker) {
    System.out.println("Cup(" + marker + ")");
  }

  void f(int marker) {
    System.out.println("f(" + marker + ")");
  }
}

class Cups {
  static Cup c1;
  static Cup c2;
  static {  
    c1 = new Cup(1);
    c2 = new Cup(2);
  }
  Cups() {
    System.out.println("Cups()");
  }
}

public class ExplicitStatic {
  static Cups x = new Cups();
  static Cups y = new Cups();

  public static void main(String[] args) {
    System.out.println("Inside main()");
  }      
} 

Output:

Cup(1)
Cup(2)
Cups()
Cups()
Inside main()

So there are two static Cups, in class ExplicitStatic, why its only showing Cup(1) && Cup(2)?

Jon Skeet
people
quotationmark

The only time that new Cup() is called is within the static initializer block for Cups.

That will only be executed once, however many instances of Cups you create - indeed, even if you don't create any instances of Cups, so long as you force the Cups class to be initialized (e.g. by calling a static method on it).

If you want two Cup instances per instance of Cups then you should use instance fields instead, e.g.

class Cups {
  Cup c1 = new Cup(1);
  Cup c2 = new Cup(2);

  Cups() {
    // This will execute *after* the field initializers above
    System.out.println("Cups()");
  }
}

Then you'd get output of:

Cup(1)
Cup(2)
Cups()
Cup(1)
Cup(2)
Cups()
Inside main()

people

See more on this question at Stackoverflow