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
Foo
is created, the object referred to beobj
will 开发者_运维技巧be instantiated?Also, will the object referred to be
obj2
only be loaded by the the JVM when the methodbar
is pushed onto the stack (invoked)?- Finally, local variables live on the stack, to am I also correct in
saying that
obj2
will 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.
精彩评论