Know your modifiers: Static

Here’s an example of a a class containing a couple of fields (class variables).

public class Player {
	public static float maxHealth = 100f;
	public float health = maxHealth;
}

The static modifier is useful for when you want a field or method to be identical to all instances of the class, or if the class you are making only ever needs one instance. A static field only exists once within a class, unlike instance fields which exist for each object you create.

In the example above, we are simulating players of a video game whom each have a health bar. I want all players to have a maximum health value of 100, so I have declared the field maxHealth which initialises to the value 100f and will never change. I also have the health field which can be changed by actions in the game. Of course, each player needs their own health variable so that different players can have different values of health, but each player does NOT need their own maxHealth variable, because it is not related to any one player instance. Because of this, we modify the field with the static modifier. This means that all Player instances will share the same maxHealth field, as it will only be created once.

The other effect of making a field static is that it can be accessed without creating any instances of the class. For example, the following statement would return the maxHealth value by accessing the class directly.

Player.maxHealth

A static field also reduces the amount of memory required by the program, as there will only be one copy of the value.

Below is a graphical representation showing how static fields and methods only exist once within the class, whereas non-static or instance fields and methods exist per-instance and are separate to each other.

Image

Advertisements

~ by Daveoh on May 1, 2013.

Leave a Reply

Please log in using one of these methods to post your comment:

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 )

Google+ photo

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

Connecting to %s

 
%d bloggers like this: