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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With