Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java array references are null after being set

Tags:

java

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.

like image 673
Josh Avatar asked Feb 12 '23 14:02

Josh


2 Answers

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.

like image 146
Konstantin Yovkov Avatar answered Feb 26 '23 23:02

Konstantin Yovkov


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.

like image 32
piet.t Avatar answered Feb 26 '23 23:02

piet.t