Static Member Variables |
Static Local 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. |
The value of the variable will be retaind.
void Increment( ) { static int num = 0; num++; } int main ( ) { Increment( ) // num becomes 1 Increment( ) // num becomes 2 Increment( ) // num becomes 3 Increment( ) // num becomes 4 } |
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( );
double value = Math.Random( );
Static Class
A static class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated. In other words, you cannot use the new operator to create a variable of the class type. Where are you could have static methods in a non static class and choose to instantiate an object.
Final Variables
Once a final variable has been assigned its value can not be changed.
final double PI = 3.14159;
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 */
}
public final class String
{
/* implementation not shown */
}
Volatile
Using the keyword volatile is necessary when the variable can be changed by an interrupt such as an event handler ( e.g. a button is pressed). This is because the CPU will have already cached the variable value, unaware that the variable might change. The keyword ensures that the CPU does gets a fresh copy of the variable data from memory.
|
|