Question about static member variables

2019-07-23 14:24发布

问题:

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

  }

回答1:

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



回答2:

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:

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