Static modifier

As mentioned on last post. Static is a non-access modifier.

For this section, we’ll explore more about static modifier.


Recall that a static method is invoked through its class name, instead of through an object of that class.

Not only can methods be static, but variables can be static as well. We declare static class members using the static modifier.

Let’s examine the implications of static variables and methods closely.


Static variable

  • A static variable, which is sometimes called a class variables, is shared among all instances of class.
  • There is only one copy of a static variable for all objects of the class. Therefore, changing the value of a static variable in one object changes it for all of the other.
1
private static int count = 0;
  • Memory space for a static variable is established when the class that contains it is referenced for the first time in a program. A local variable declared within a method cannot be static.
  • Constants, which are declared using the final modifier, are often declared using the static modifier. Because the value of constants cannot be changed, there might as well be only one copy of the value across all objects of the class.

Static Methods

  • Static methods can be invoked through the class name. We don’t have to instantiate an object of the class in order to invoke the method.
  • A method is made static by using the static modifier in the method declaration.
1
2
3
4
public static int getCount()
{
return count;
}
  • As we’ve seen many times, the main method of a Java program must be declared with the static modifier;
  • This is done so that main can be executed by the interpreter without instantiating an object from the class that contains main.
1
2
3
4
public static void main (String[] argc)
{

}
  • Because static methods do not operate in the context of a particular object, they cannot reference instance variables, which exist only in an instance of a class. The compiler will issue an error if a static method attempts to use a nonstatic variable.
  • A static method can, however, reference static variables, because static variables exist independent of specific objects. Therefore, the main method can access only static or local variables.

Source code: Camilla904/1620ITEC