static Methods and VariablesPurpose:
- 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:
staticis one of several possible modifiers that can appear anywhere in the space-separated list of modifiers.- A method which is declared
staticcan 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
staticvariable for all instances of the class. Therefore, if one instance changes the value of astaticvariable, that change is seen by other instances of the class.
Restrictions:
- Since a
staticmethod can be executed without an instance of the class which contains it existing, no statement in the definition of that method can refer tothis. - A
staticmethod can refer to other methods and instance variables of the class which contains it only if they are also declaredstatic. - A
staticmethod is implicitlyfinal, so it cannot also be declaredabstract, and cannot be redefined in a subclass. Inclusion of thefinalmodifier is optional.
email suggestions to: cs015tas@cs.brown.edu
