开发者

When is an object declared and initialized in a local reference created in Java?

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)?

  • 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜