开发者

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

开发者 https://www.devze.com 2023-03-27 18:32 出处:网络
If I have the following code: public class Foo { private Object obj = new Object(); public void bar() { final Object obj2 = new Object();

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

精彩评论

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

关注公众号