If I have the following code:
public class Foo {
private Object obj = new Object();
public void bar() {
final Object obj2 = new Object();
}
}
-
Am I correct in stating that when a new instance of
Foois created, the object referred to beobjwill be instantiated? -
Also, will the object referred to be
obj2only be loaded by the
the JVM when the methodbaris pushed onto the stack
(invoked)? - Finally, local variables live on the stack, to am I also correct in
saying thatobj2will live on the stack, while the object it refers
to lives on the heap?
That is the case. Objects in scope of a method will be only instantiated when the method is called, while members of a class so declared will be instantiated when the object is constructed.