4
public abstract class Class1 {
    protected static Object object1 = null;
    protected static Object object2 = null;

    public static Object[] objects = { object1, object2 };

    public static void main(String[] args) {
        new Class2();

        for (Object o : objects) {
            System.out.println(o);
        }
    }
}

public class Class2 extends Class1 {
    public Class2() {
        Class1.object1 = new String("String 1");
        Class1.object2 = new String("String 2");
    }
}

This outputs:

null
null

Why?

When I create a new instance of Class2, the constructor for that class initializes object1 and object2.

objects, as far as I know, contains references to these Objects. So after they're initialized, I expected anything but null.

Could someone explain? Thanks.

Josh
  • 6,046
  • 11
  • 52
  • 83
  • `int x = 3; int y = x; x = 5;` y is still 3. – Jason C Nov 11 '14 at 14:59
  • @SotiriosDelimanolis *Slightly* disagree with duplicate as the link is about function parameters, and even though it's the same idea, it would be difficult for the OP here to make that jump. – Jason C Nov 11 '14 at 15:03
  • If you didn't catch it earlier, please read [this](http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value). – Sotirios Delimanolis Nov 11 '14 at 15:11

2 Answers2

5

object doesn't contain references to these object1 and object2, but contains copied references to these objects.

If you do:

public static Object[] objects;

public static void main(String[] args) {
    new Class2();

    objects = { object1, object2 };
    for (Object o : objects) {
        System.out.println(o);
    }
}

i.e. initialize object after you initialize object1 and object2 you will have copies in the array that are not empty.

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
3

When instanciating your object first this

protected static Object object1 = null;
protected static Object object2 = null;

sets object1 and object2 to be null-references.

Then this

objects = { object1, object2 };

copies the references that object1 and object2 contain at that time to objects[0] and objects[1].

Then here

    Class1.object1 = new String("String 1");
    Class1.object2 = new String("String 2");

you create new String-references that get stored in object1 and object2 - but the copies in objects[0] and objects[1] are unaffected.

piet.t
  • 11,718
  • 21
  • 43
  • 52