CSCI 136 - What's the Story with static?

We have seen and will continue to see the static keyword being used in front of method and variable declarations. It is often a source of confusion among beginning (and, for that matter, some very experienced) programmers.

Basically, the keyword static says that the method or variable should be associated with the class rather than with a specific instance of the class. The class can be thought of as a blueprint from which a new instance is constructed (with the new operator). static things (class variables and class methods) are associated with that blueprint, while non-static things (instance variables and instance methods) are associated with individual constructed objects.

Consider a class which includes the following variable declarations:

public class Example {

  protected int a, b;
  static protected int c;
}
and some code in some other class that creates two instances of Example:
  Example ex1 = new Example();
  Example ex2 = new Example();
This leads to memory allocation that looks like this:

Each instance of Example can access the same class variable c, and in fact this (if declared as public rather than protected) class variable could be accessed as Example.c even if no instance of Example was ever created. It exists exactly once no matter how many instances of Example are created. The instance variables a and b have separate copies associated with ex1 and ex2.

For methods, we just need to remember that any method which needs access to instance variables cannot be declared as static. These instance methods have access to their instance variable, to the class variables, and to their parameters and local variables. If a method does not need to access instance variables, it may be declared as static. It can still access class variables, parameters, and local variables. This is a requirement of a main method, since no instance of any class has been constructed when main is called by the Java Virtual Machine. There are many class methods defined, for example, in the Math class. These are functions like Math.sqrt() and Math.pow() which can do everything they need just using their parameters, and do not need to retain any state information from one call to the next.

In programs for this course, the issue comes up because main is always declared static. There are a number of examples from the course that have main construct one or more instances of the class in which it resides to be able to make use of instance methods and variables. In other cases, we have a main method in a separate class.