Question about static member variables

2019-07-23 13:44发布

In the following code, 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() {

  }

3条回答
够拽才男人
2楼-- · 2019-07-23 14:23

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.

查看更多
我想做一个坏孩纸
3楼-- · 2019-07-23 14:32

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

查看更多
老娘就宠你
4楼-- · 2019-07-23 14:34

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()).

查看更多
登录 后发表回答