0

I'm testing the result of this code, to realise how the static object creating works. Basically i understood everything till the last System.out.println(" " + a[0]); I ran the debugger, and i verified that in that point, all of the elements of the array have the same value on num variable. Can anyone explain me why is it happen?

static class Numero {

    private static int sn = 0;
    private int num;

    public Numero(int n) {
        num = n;
        ++sn;
    }

    public void setNum(int n) {
        num = n;
    }

    public String toString() {
        return "num = " + num + " sn = " + sn;
    }
}

public static void main(String[] args) {

    Numero[] a = new Numero[3];
    Numero x = new Numero(12);

    for (int i = 0; i < a.length; i++) {
        a[i] = x;
        a[i].setNum(i);
        System.out.println("  " + a[i]);
    }
    System.out.println("  " + a[0]);
}

Output:

  num = 0 sn = 1
  num = 1 sn = 1
  num = 2 sn = 1
  num = 2 sn = 1
1
  • Because once you created the only instance of You Numero Object, you are saving reference to it in each array entry Commented Jun 29, 2015 at 20:46

4 Answers 4

1

This is because your Numero object is mutable. When you modify it in any way, all references to it are modified as well.

When you call a[i] = x:

  • You don't create a copy of x and put it in position i.
  • You do store a reference to x at position i.

So, by the end of your iteration, your array has stored three references to the same object (you can think of it as {x, x, x}). And since that object has changed throughout the loop (because a[i].setNum(i) is equivalent to x.setNum(i)), your last output prints the num value as 2.

Sign up to request clarification or add additional context in comments.

Comments

1

You created a single Numero, so sn got incremented once, to 1. That same instance got assigned to each element of a; you saw different values for num because you printed it out at different times.

Comments

1

Making a static class essentially enforces the singleton design pattern. The class can only have static methods and static instance fields. Static instance fields hold the same value across all instances of the class, and you can think of it as all objects of that class sharing the same variable instead of having copies of it.

When you print a[0] in the loop, you get what you expect, but after the loop, that static ("shared") variable was changed by other objects, leaving num to be the value of 2, set by the last iteration of the for loop.

Comments

1

issue lies here

a[i] = x;

a[i] is pointing to X now , so whenever you call setNum method ,method belongs to X .so you will get same instance output always

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.