Static Variables

A static variable is useful when you have a common property which will be the same for objects of that class. For example all Cars objects may share the same variable TotalCarsMade which is incremented every time an object is instantiated. It would be declared as static in the Cars class as:

static int TotalCarsMade = 0;

A static variable thus belongs to the class and not to the object. If its value is changed, it changes for all objects. Static variables should be declared as private so that another class does not accidentally change their value.

Static Methods

Static methods are invoked by the the class not the object. This means that to use a static method you don't have to create an instance of the class as an object. You know this from using the Math class where you have used the following static Random() method. You haven't needed to create a Math object first.

double value = Math.Random();

Final Variables

Once a final variable has been assigned its value can not be changed.

final double PI = 3.14159;

Final Methods

A method defined as final can not be overridden by subclasses.

Static and final combined

You can declare variables as both static and final to create a variable shared by all objects which can not be changed after it is initialised.

static final int DAYS_IN_WEEK = 7;

Final Class

A final class can not be extended. The string class is an example of a final class:

public final class String
{
    /* implementation not shown */
}