static Methods and Variables

Purpose:

To declare a method or instance variable as owned by a class, rather than instances of that class.

Mechanics:

static <other modifiers> <return type> <method name>(<parameter list>) {
/* Java statements here */
}

static <other modifiers> <data type> <variable name>;

Example:

static void myMethod() {
/* Java statements */
}

static int myNumber;

Usage:

  • static is one of several possible modifiers that can appear anywhere in the space-separated list of modifiers.
  • A method which is declared static can be accessed without first creating an instance of the class which contains it.
  • While an instance of a class normally gets its own set of instance variables when it is created, there exists only one instantiation of a static variable for all instances of the class. Therefore, if one instance changes the value of a static variable, that change is seen by other instances of the class.

Restrictions:

  • Since a static method can be executed without an instance of the class which contains it existing, no statement in the definition of that method can refer to this.
  • A static method can refer to other methods and instance variables of the class which contains it only if they are also declared static.
  • A static method is implicitly final, so it cannot also be declared abstract, and cannot be redefined in a subclass. Inclusion of the final modifier is optional.
Back to the Table of Contents
email suggestions to: cs015tas@cs.brown.edu