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.

3
  • int x = 3; int y = x; x = 5; y is still 3. Commented Nov 11, 2014 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. Commented Nov 11, 2014 at 15:03
  • If you didn't catch it earlier, please read this. Commented Nov 11, 2014 at 15:11

2 Answers 2

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.

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

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.