Java array references are null after installation

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");
    }
}

It is output:

null
null

Why?

When I create a new instance Class2, the constructor for this class initializes object1and object2.

objectsas far as I know, contains links to these objects. Therefore, after initialization, I expected nothing but zero.

Can someone explain? Thank.

+4
source share
2 answers

objectdoes not contain links to these object1and object2, but contains copied links 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 objectafter initialization object1and object2you will have copies in the array that are not empty.

+5
source

,

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

object1 object2 null -references.

objects = { object1, object2 };

, object1 object2 objects[0] objects[1].

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

String -, object1 object2, objects[0] objects[1] .

+3

All Articles