Reputation: 7327
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 be obj
will be instantiated?
Also, will the object referred to be obj2
only be loaded by the
the JVM when the method bar
is pushed onto the stack
(invoked)?
obj2
will live on the stack, while the object it refers
to lives on the heap?Upvotes: 1
Views: 94
Reputation: 10077
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.
Upvotes: 3