#670 – Static vs. Instance Initialization

Static fields and properties are data members associated with a class itself, rather with instances of that class.  A static constructor can be used to initialize static members.  Static fields can also be initialized when they are declared.

The first time that you reference a static member, the following occurs:

  • All static fields are initialized
  • The static constructor is called
  • Your code, which accesses the static member, executes

If you reference an instance method, or create an instance of the class, before referencing any static members, the following occurs:

  • All static fields are initialized
  • The static constructor is called
  • All instance fields are initialized
  • The instance constructor is called
  • Your code, which accesses an instance member, executes

For example, initializing an instance of a Dog leads to the output shown below.

Dog d = new Dog();

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: