dfetter88
dfetter88

Reputation: 5391

Question about static member variables

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

  }

Upvotes: 2

Views: 201

Answers (3)

Paul Sonier
Paul Sonier

Reputation: 39480

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

Upvotes: -1

Jarek Potiuk
Jarek Potiuk

Reputation: 20047

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

Upvotes: 6

James Scriven
James Scriven

Reputation: 8134

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.

Upvotes: 4

Related Questions