开发者

Question about static member variables

开发者 https://www.devze.com 2023-03-16 09:15 出处:网络
In the following code开发者_JS百科, it is my assumption that the member variable mBar will only be instantiated upon the first construction of a Foo object... and that this mBar instantiation will be

In the following code开发者_JS百科, it is my assumption that the member variable mBar will only be instantiated upon the first construction of a Foo object... and that this mBar instantiation will be shared with all future Foo objects, but the Bar() constructor will not be called again. Is this accurate?

public class Foo {
  private static Bar mBar = new Bar();

  public Foo() {

  }


The object might actually be constructed WAY before creation of first Foo.. It will be executed when Classloader loads the Foo.class in memory and this can happen pretty much at any time.... Specifically when you load other classes that use Foo class, or when you call a static method of the class....


Almost, it will get instantiated when the class Foo is first loaded. So if you call Foo.mBar (if it were public) you would get the bar instance, even though no instances of Foo have been instantiated.


Your assumptions are mostly accurate. mBar only gets initialized once for all instances of the class (in the same process). Note that that doesn't stop any other classes from calling the Bar constructor...

Edit: as pointed out in the comments, it won't necessarily be upon the first construction of a Foo object; it's the first executing reference to a Foo object that will cause the classloader to initialize the static members (thereby calling Bar()).

0

精彩评论

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