So lets assume the following classes definition:
public class A {
private B b;
public A() {
b = new B();
}
}
public class B {
private C c;
public B() {
c = new C();
}
}
public class C {
public C() {
}
}
public class X {
private A a;
public X() {
}
}
Now let assume that the following main is being executed:
public static final void main (String[] argv) {
X x = new X();
}
Here an instance of X
is create in the memory heap and a reference to this object is store in the x
variable.
Since no value is assign to the a
variable during the class construction, then no instance of A is created. The a
variable still takes up space in memory as part of the instance of X
that was created (in other words, it still needs enough space to be able to store a reference), but in this case a
is assigned the null
value (from Java Language Specification §4.12.5)
For all reference types (§4.3), the default value is null.
Now lets modify the X
class as follow
public class X {
private A a;
public X() {
a = new A();
}
}
If we were to execute the main()
method again with this modified version of X
, then as part of the construction process, X
would cause an instance of A
to be created which would cause an instance of B
to be created which in turn would cause an instance of class C
to be created. All these instances would take up space in the memory heap and the reference to these objects would be stored in their respective variables.