Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

  }
like image 500
dfetter88 Avatar asked Jan 21 '26 19:01

dfetter88


2 Answers

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

like image 155
Jarek Potiuk Avatar answered Jan 23 '26 07:01

Jarek Potiuk


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.

like image 21
James Scriven Avatar answered Jan 23 '26 09:01

James Scriven